I am having an interesting problem that I can't seem to suss out while working on a bubble sort problem. Take in up to 25 integers and sort them from lowest to highest value and reprint the array. This is the code I have written up that logically works on paper:
#include <iostream>
void bubbleSort (int unsorted[25], int sorted[25], int numItems);
void getInput (int unsorted[25], int toSort[25], int& numItems);
void printArray (int toPrint[25], int& numItems);
int main () {
int numItems = 25;
int unsorted[25];
int sorted[25];
getInput(unsorted, sorted, numItems);
printArray(unsorted, numItems);
bubbleSort(unsorted, sorted, numItems);
printArray(sorted, numItems);
return 0;
}
void bubbleSort (int unsorted[25], int sorted[25], int numItems) {
int temp;
for (int i = 0; i < numItems; i++)
for (int j = 0; j < numItems - i; j++)
if (sorted[j] > sorted[j+1]) {
temp = sorted[j];
sorted[j] = sorted[j+1];
sorted[j+1] = temp;
}
}
void getInput (int unsorted[25], int toSort[25], int& numItems) {
int val;
cout << "Please enter up to 25 integers, one at a time\n"
<< "If less than 25 are to be added, enter '-999' to stop\n";
for (int i = 0; i < 25; i++) {
cin >> val;
if (val == -999) {
numItems = i;
break;
}
unsorted[i] = val;
toSort[i] = val;
}
cout << "\nUser input complete\n";
}
void printArray (int toPrint[25], int& numItems) {
for (int i = 0; i < numItems; i++)
cout << " [" << toPrint[i] << "] ";
cout << endl;
}
The problem I am experiencing is that given the same input, in my case I am using [3, 2, 4, 1, 5] as it was what initially tipped me off to the bug, I can get different output. specifically one of these two with seemingly no rhyme or reason that I can see :
User input complete
[3] [2] [4] [1] [5] -> entered numbers
[0] [1] [2] [3] [4] -> sorted numbers
or :
User input complete
[3] [2] [4] [1] [5] -> entered numbers
[1] [2] [3] [4] [5] -> sorted numbers
Both outputs are from the same compiled program and seems to just randomly decide if it'll chop off my highest value and replace it with a 0. I know it isn't actually random but I can't figure what is causing it for the life of me.
In your sort function, change
for (int j = 0; j < numItems - i; j++)
to
for (int j = 0; j < numItems - i - 1; j++)
Because if i
is 0, there will be j < numItems
, and sorted[j] = sorted[j+1]
will be out of range.