Sort an array with unknown length

Hi,

I am writing a program that prompts the user to enter values that will be stored in an array. When user chooses not to add new values (by typing N), the program will output the array in ascending order. The input values should be stored as floats, and the program should be able to process up to 100 values, and as few as 0 values. As the number of values entered by user is unknown, how can I use a bubble sort algorithm to sort the array? I'm confused as to how to declare the array when the length is unknown, and how to structure the function. Any assistance will be greatly appreciated!

Will it be correct to declare a global variable (constant) as the max number?

const int MAX = 100;

and then declare the array below the int_main function:

float myarray[MAX];

function I've been using:

sort(myarray, myarray + MAX);

for (int i = 0; i <= MAX; ++i)
cout << myarray[i] << ' ';
Two things.

If you're going to have them just keep putting in numbers until they type 'n', then you're better off with a Vector.
1
2
3
4
5
6
7
8
9
10
11
vector <float> myVector;
int vectorIndex = 0;

cin >> //something;

while(/*somehow test that input isn't 'n'*/){
    myVector.push_back();
    myVector[vectorIndex] = /*number user input*/;

    cin >> //something;
}


The problem with this is if you're testing by input if it's a float or the character 'n', you're not going to have a fun time.

The other way is to have the person declare at the start how many numbers they will put in. Then you can do this:
1
2
3
4
5
6
int n;
float *array;

cin << n; // amount of numbers you plan to enter

array = new float [n];


Then you can just use a for-loop to let the user input each element of the array.

If you can, go with the second option. Also, read up on vectors!
Last edited on
Assuming you can't use a vector, the easiest way would probably be to just count the number of valid input values. Then the sort would be sort(myarray, myarray + (count - 1));
Topic archived. No new replies allowed.