### Sorting Arrays

I have to make an array with 20 double digit numbers in it randomly then bubble sort them into a different array. I keep getting errors when I am trying to run it and I am getting negative numbers in my arrays instead of regular numbers.

I assume it's something simple and I am making a dumb mistake.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061`` `````` #include #include #include #include #include #include using namespace std; //constant const int MAX = 20; //prototype int main() { srand(time(NULL)); //variables int original[MAX]; int sorted[MAX]; int quantity = 0, sum = 0, x = 0; double avg; int i, j; for (j = 0; j < 20; j++) { i = rand()%99+10; original[i]=i; } //input //calculations for (i = 0; i <= 19; i++) { for (j = i + 1; j <= 20; j++) { int temp; if (original[i] > original[j]) { temp = original[i]; original[i] = original[j]; original[j] = sorted[j]; } } } for (i = 0; i <= 19; i++) { cout << sorted[i]; } //output return 0; }``````
Last edited on
For a random number from Min to Max, inclusive:

 `` `` ``rand() % (Max - Min + 1) + Min;``

You are also using the wrong array index to load the array. Don't use the random number!

 ``1234`` ``````const int ArrSize = 20, Min = 10, Max = 99; for (int i = 0; i < ArrSize; i++) original[i]= rand % (Max - Min + 1) + Min;``````

Then you should copy it to the "sorted" array and sort that. "original" should not be mentioned in the bubble sort. And remember to use ArrSize and ArrSize-1 instead of 20 and 19.
Hello Shawske,

 I keep getting errors when I am trying to run it

https://www.dictionary.com/e/slang/42/

If you are going to keep your errors a secret no one can help.

You sort the original array, but you print out the uninitialized sorted array.

Try changing the for loop that should be under the "input" section to:
 ``1234567`` ``````for (j = 0; j < 20; j++) { i = rand()%99+10; original[i] = i; sorted[i] = i; // <--- Saves on copying later. } ``````

Then under the "calculations" heading, which should be "sort" , because you are not calculating anything. Sort the "sorted" array not the original.

 ``123`` ``````int original[MAX]{}; int sorted[MAX]{}; double avg{};``````

The empty {}s will initialize the arrays to all (0) zeros. and the double to "0.0". It is always a good idea to initialize your variables.

A few blank lines in your code make it much easier to read and follow.
 ``123456789101112`` ``````int main() { srand(time(NULL)); //variables int original[MAX]; int sorted[MAX]; int quantity = 0, sum = 0, x = 0; double avg; //int i, j; // <--- Should be defined in the for loops unless you really need them later. for (int j = 0; j < 20; j++)``````

This should work, but at this moment I have not tested it.

Andy
Topic archived. No new replies allowed.