int numbers [30];
int numbersSorted[30];
int menuChoice;
int bubbleCounter=0;
ifstream file;
file.open("nums.txt");
for (int j=0;j<30;j++)
{
file >> numbers[j];
}
for (int j=0;j<30;j++)
{
numbersSorted[j]=numbers[j];
}
while (menuChoice!=8)
{
cout << "1. Show unsorted list" << endl;
cout << "2. Show sorted list" << endl;
cin >> menuChoice;
cout << endl;
switch (menuChoice)
{
case 1:
cout << "The numbers are:" << endl;
for (int j=0;j<30;j++)
{
cout << numbers[j] << endl;
}
cout << endl;
break;
case 2:
for (int j=0;j<30;j++)
{
for (int i=0;i<30-bubbleCounter;i++)
{
if (numbersSorted[i]> numbersSorted[i+1])
{
int x=numbersSorted[i+1];
numbersSorted[i+1]=numbersSorted[i];
numbersSorted[i]=x;
}
}
bubbleCounter++;
}
for (int j=0;j<30;j++)
{
cout << numbersSorted[j] << endl;
}
cout << endl;
break;
When I sort the array "numbers" in case 2 and output it, the greatest number is 95 (which it should be). But when I use the array "numbersSorted" in case 2, and output it, the greatest number is the second greatest number in the 30 numbers, 94.
Ohh ok, I will post all code from now on. I made bubbleCounter equal to 1 now, and it works with numbersSorted. But why did it work for the array "numbers" even when bubbleCounter was 0? I'm wondering because numbersSorted and numbers start off as the same array.
If it accesses beyond array bounds then it takes whatever happens to be in that memory slot ... which could be anything ... and could even give different answers on different machines or with different compile options.
In c++, "lucky dip" may not be all that good; I'd avoid going beyond array bounds.