# C++: Specific Array Elements Do Not Appear With Bubble Sorting and Binary Search

+Problem: When doing the Binary search, only the middle element consistently comes out correct. The other elements, when searched for, provide blank space instead of a number. Picture: http://i.imgur.com/7JOoCwk.png

Assignment information: Write a program that prompts the user to enter the number of elements and the numbers themselves to be placed in an integer array that holds a maximum of 50 elements. The program should then prompt the user for an integer which will be searched for in the array using a binary search. Make sure to include the following steps along the way:

1) A sort routine must be called before the binary search. You may use either the selection sort or the bubble sort. However, the sort must be implemented in its own function and not in main.

2) Next include a function called by main to implement the binary search. The ordered array produced by the sort should be passed to the search routine which returns the location in the sorted array of the sought value, or -1 if the value is not in the array.

3) Add a value returning function that computes the mean of your data set. Recall that the mean is the sum of the data values divided by the number of pieces of data. Your program should output the size of the array entered, the array as entered by the user, the sorted array, the integer being searched for, the location of that integer in the sorted array (or an appropriate message if it is not in the array), and the mean of the data set.

#include<iostream> using namespace std; void bubbleSort(int [], int); int searchBinary( int[], int, int); void displayArray(int[], int); int main () { int userValue; const int SIZE = 50; int numArray[SIZE]; cout << "Enter the element numbers to be placed into the integer array." << endl; for (int count = 0; count < SIZE; count ++) { cout << "enter integer #" << count + 1 << " "; cin >> numArray[count]; /*if (numArray[count] ==0) break; */ } bubbleSort (numArray, SIZE); cout << "The array has been sorted." << endl; displayArray(numArray,SIZE); cout << "what integer would you like to retrieve?"; cin >> userValue; cout << "Searching the array..." << endl; cout << "The value you retrieved is "; cout << searchBinary(numArray, SIZE, userValue); return 0; } void bubbleSort (int arrayNumx[], int ELEMS) // bubbleSort function definition { bool elemswap; int temp1 = 0; int endValue = ELEMS - 1; do { elemswap = false; for (int count = 0; count < endValue; count ++) { if (arrayNumx[count] > arrayNumx[count+1]) { temp1 = arrayNumx[count]; arrayNumx[count] = arrayNumx[count + 1]; arrayNumx[count+1] = temp1; elemswap = true; } } endValue--; } while (elemswap != false); } //searchBinary function header int searchBinary (int intArray[], int totalElems, int quantity) //searchBinary function definition { int first = 0 ; int last = totalElems -1; int middle = 0; int returnnum = -1; while (first <= last) { middle = (first + (last-first))/2; if (intArray[middle] == quantity) return middle; else if (intArray[middle] < quantity) first = middle + 1; else last = middle - 1; } return -1; } void displayArray (int shownum[], int dec) { for(int count = 0; count < dec; count++) cout << shownum[count] << endl; }

## Answers

The most common error in binary searching is forgetting the *both* sides of a split are not necessarily the same length. I.e. when you calculate this:

middle = (first + (last-first))/2;

and then use middle as the comparative element, you need to remember that the size of the remaining partition is not always (last-first)/2. Due to integer division there may well be one more element on one side of the partition than the other.

For example, the simple sequence of 8 elements in order:

1 2 3 4 5 6 7 8

Initially we have a sequence that is 8 elements long. we'll choose 8/2, i.e 4, as the mid-point, which gives us this (remember our indexing is **zero-based**):

1 2 3 4 5 6 7 8 ------- X -----

Ok. unless the element we're looking for is 5, we are either going up, or down. But what is the difference (besides the obvious)? Well if what we want is *greater* than 5, then this is where we'll be looking

1 2 3 4 5 6 7 8 -----

i.e. a **three** element sequence remains. However, if we need to move to the *low* side (the value is *less* than 5) then we'll have the following left to conquer:

1 2 3 4 5 6 7 8 -------

i.e. a **four** element sequence remains.

To consistently make sure you don't skip elements, accurately maintain the following:

- The base index, which only adjusts when moving to a higher partition split.
- The current sequence length, adjusted with each partition.
- The mid-point calculation within the current sequence.

This is one way to do all of the above.

size_t bin_search(int arr[], size_t len, int value) { if (len < 1) // here for sanity sake return (size_t)-1; size_t base=0, mid=len/2; while (len > 1) { if (arr[base+mid] < value) { base += (mid+1); // relocate base len -= (mid+1); // remaining length } else if (value < arr[base+mid]) { // no change in base; length split len = mid; } else return base+mid; // quick exit, found match // next midpoint length based on updated sequence length mid = len/2; } return (arr[base+mid] == value) ? base+mid : -1; }

Best of luck.