### Help with bubbleSort

closed account (z8q4izwU)
Hello im having issues with this code, it turns the number 9999 when outputted into 58 and cant figure out why. If any one can help id appreciate it.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778`` ``````#include #include using namespace std; void bubbleSort(int list[], int listLength); int binarySearch(int list[], int searchItem, int listLength); const int LIST_LENGTH = 10; int main() { int list[] = {4, 703, 62, 1111, 666, 1337, 9583, 1, 1234, 9999}; int search; int loc; bubbleSort(list, LIST_LENGTH); cout << "Enter the number you wish to search for: "; cin >> search; loc = binarySearch(list, search, LIST_LENGTH); if (loc == -1) { cout << "The number entered could not be found"; } else { cout << "The number's location is: " << loc; } cout << endl; /* to check what is currently in list[] */ for (loc = 0; loc < 10; loc++) { cout << list[loc] << " "; } cout << endl; system("PAUSE"); return 0; } void bubbleSort(int list[], int listLength) { int temp; for (int it = 0; it < listLength; it++) { for (int i = 0; i < listLength - it; i++) { if (list[i] > list[i+1]) { temp = list[i+1]; list[i+1] = list[i]; list[i] = temp; } //end if } //end for } //end for } //end bubbleSort int binarySearch(int list[], int searchItem, int listLength) { bool found = false; int min, max, mid; min = 0; max = listLength - 1; while (!found && min <= max) { mid = (min + max) / 2; if (list[mid] == searchItem) { found = true; } else if (list[mid] > searchItem) { max = mid - 1; } else { min = mid + 1; } //end if...else } //end while if (!found) { return -1; } else { return mid; } //end if...else } //end binarySearch ``````
Line 44 is checking an element outside the bounds of the array.
`for (int i = 0; i < listLength - it; i++) {`
when it=0, i will range from 0 to listlength-1
hence `list[i+1]` is list[listlength] which is past the last element. That's the cause of unexpected results.

Change line 43 to
` for (int i = 0; i < listLength - it - 1; i++) {`

And just a suggestion, your search works ok. But when you find the element, the function could return immediately, like this.
 ``123456789101112131415161718192021`` ``````int binarySearch(int list[], int searchItem, int listLength) { int min = 0; int max = listLength - 1; while (min <= max) { int mid = (min + max) / 2; if (list[mid] == searchItem) return mid; if (list[mid] > searchItem) { max = mid - 1; } else { min = mid + 1; } } return -1; }``````
Last edited on
closed account (z8q4izwU)
Thank you for the help!
Topic archived. No new replies allowed.