I'm working on a school assignment where the task is to sort an array in ascending order. I've run into trouble with the bubble sorting. When the array starts to sort, it does sort, but the biggest integer of the array is getting switched to a random integer.
Don't mind the choice variable and the input. The task is supposed to have the possibility to choose whether you want to sort ascending or descending. In this code I've only reached the ascending sorting.
I'm printing out the array for each run through for my own, to see how the bubble sorting is working.
Why is the biggest number being switched to, in this case, -13248??? Using cygwin compiler if that is good info for anyone to know.
int main()
{
int number[] = {900,800,700,697,512,455,318,217,143,32};
int swapHolder = -1;
int end = 10;
int length = 10;
string choice;
cout << "This is an array of ten integers." << endl;
for(int i=0; i<10; i++)
{
cout << number[i] << ", ";
}
cout << endl;
cout << "Choose whether you want to sort the array in ascending or descending order." << endl;
cout << "Type ASC for ascending or DESC for descending." << endl;
cin >> choice;
if(choice == "ASC")
{
for(int counter = length - 1; counter >= 0; counter--)
{
for(int index = 0; index < end; index++)
{
if (number[index] > number[index+1])
{
swapHolder = number[index+1];
number[index+1] = number[index];
number[index] = swapHolder;
}
}
for(int index = 0; index < 10; index++)
{
cout << number[index] << ", ";
}
cout << endl;
end--;
}
}
return 0;
}
Output:
You are exceeding the array's bounds and swap in an (uninitialized) value right after that array. Note that your array contains 10 elements, i.e. 0..9
, and an access to number[10]
is not permitted. In your code index
runs up to 9
, and you access number[index+1]
, which actually means number[10]
then:
int end = 10;
for(int index = 0; index < end; index++)
{
if (number[index] > number[index+1])
{
swapHolder = number[index+1];
number[index+1] = number[index];
number[index] = swapHolder;
}
}
Though being actually undefined behaviour, common behaviours are that the program either crashes or accesses (and uses) memory that has not been initialized and therefore contains some "random" values, e.g. -13248
.