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];
}

You're definitely on the right track, but because you have to do it while entering/generating the values, you actually have to use a variation on the "insertion sort" algorithm. A bubble sort could work, but it's extremely inefficient and doesn't meet the specifications/parameters of the assignment.

Here is some information on insertion sort.

Initially, you'll want to store the random value to a temp value not as a member of the array. Then send the temp value to the function. Inside the function, you'll find where the value belongs then "slide" the values/elements above it. Once the "slide" is complete, you then assign it to the appropriate array element.

Edited 5 Years Ago by Fbody: n/a

Comments
Managed to fix my problem thanks to this post

Thank you so much! Insertion sort worked for me.
You were very helpful.

This question has already been answered. Start a new discussion instead.