I have a code that generates 40 random numbers from 50~100 and put them in array and then sort it from smallest to largest. also print out 5 smallest at the end
I really don't know why but first number in my array is always 40.
everything else looks fine.
I don't get 40, I get garbage which is consistent with what ne555 said. Just for the heck of it, try changing the conditions in your for loops to x < n - 1 and i < n - 1.
When I try to compile this, I get an error at line 7:
/.../Test/main.cpp||In function ‘int random()’:|
/.../Test/main.cpp|26|error: new declaration ‘int random()’|
/usr/include/stdlib.h|327|error: ambiguates old declaration ‘long int random()’|
||=== Build finished: 2 errors, 0 warnings ===|
There is already a longint random(); function in some versions of cstdlib. I changed all references from random() to random50() and now it at least compiles for me, however instead of 40 for my first number, I get 0. I'll keep looking.
Got it:
Replace line 37: for (int i = 0; i < n; i++)
with: for (int i = 0; i+1 < n; i++)
On your last iteration, of this loop i is 39. Then you perform operations on a[i+1] which is a[40] which is not part of the array. This is a value which shouldn't be accessed. It could cause a seg fault. In my compiler it happened to be 0, in your compiler it happened to be 40. Tomorrow when you boot up, you may find that it is something else.
You are trying "Bubble Sort" the wrong way. That is why when sorting it always gives the first element of array the value of ArraySize...
Try this one and it will work....
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void sort(int a[], int n)
{
int temp;
for (int x = 1; x <= n ; x++)
{
for (int i = 0; i < n-x; i++)
{
if (a[i] > a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
}
}