Hi, I was wondering if you can help me figure how to go about this problem.
This is what I have to do:
Write a programme to generate an array of 100 random integers.
While the array is being filled incrementally, produce a sorted array by comparing the new element n+1 to a sorted array of n elements and inserting the new element into the appropriate position (this mean shifting all larger elements into one position up in the array).
This process will ultimately produce a sorted list of the 100 random numbers.
This is what I have so far.. I understood that there needs to be a function, that sorts out the array, while its being filled and produces new array.
I tried to use bubble sort in the function, but it doesnt appear to sort the array.
Can somebody please advice how can I fix this or is there a better way to go at it?
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int arraysort(int array[], int num, int size);
int main()
{
int array[100], i, size = 0;
srand(time(NULL));
for(i=0; i<100; i++){
array[i] = rand();
size++;
array[i] = arraysort(array, array[i], size);
}
for (int i=0; i<100; i++) cout << array[i] << " ";
return 0;
}
int arraysort(int array[], int num, int size){
int a, b, t;
if (a == 0) return num;
for (a=1; a<size; a++)
for (b=size-1; b>=a; b--) {
if(array[b-1] > array[b]) {
t=array[b-1];
array[b-1] = array[b];
array[b] = t;
}
}
for (t=0; t<size; t++)
return array[t];
}