This code compiles and runs, outputs what I want, but still produces an error. From what I understand this is undefined behavior, but to me this all seems pretty novel, all pretty understandable. What doesn't my compiler understand about it?
I also did figure out how to make the errors go away, in that I changed the maximum i iteration to be 8, or less than 9, but why is it considered a bad practice to rerun the loop in case you didn't end up sorting it properly, say I had user input?
#include <iostream>
usingnamespace std;
int main()
{
//to bubble sort, run through an array, record a value, if it's lower than the next, keep it, if higher than the next, swap it.
//redo this length times.
int intArray[10] = {10,9,8,7,6,5,4,3,2,1};
int temp;
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
if(intArray[i] > intArray[i+1])
{
temp = intArray[i];
intArray[i] = intArray[i+1];
intArray[i+1] = temp;
}
}
}
for(int i = 0; i < 10; i++)
{
cout << "Int array " << i << ": " << intArray[i] << endl;
}
}
Actually, you can do better. Each pass puts another "sorted" one at the end, so:
(1) Once you've put the largest 9 in place, the final one is automatically in place. So you need 9 (or, in general, size-1) passes in j. Thus j=0 and j<9 would be Ok here.
(2) Each pass doesn't have to be as long, since each pass puts another one in a sorted position at the end. Hence, the i loop doesn't need to be as long; the loop condition could be i<9-j.
And it would be better if you didn't use the "magic number" 10.
Set
const int size = 10;
at the start and then (after making the changes above) replace every 10 by size, and every 9 by size-1.