Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Mar 21st, 2010 | Syntax: C++ | Size: 2.00 KB | Hits: 93 | Expires: Never
This paste has a previous version, view the difference. Copy text to clipboard
  1. //Here is the function that takes 1 generic array argument, 1 size of the array generic argument, and 1 value which represents what is being looked for.
  2. int binarySearch(int myArray[], int totalElements, int value)
  3. {
  4.         int beginingElement = 0;//represents the starting poing of the array subscript 0
  5.         int lastElement = totalElements - 1;//represents the last point in the array subscript last spot minus 1
  6.         int middle;//Represents the middle point of the array
  7.         int position = -1;//this is the return once the value was found.  It is set to -1 cause this lets us know that the value has not yet been found.
  8.         bool found = false;//This represents weather the value has been found yet or not as a true false boolean.
  9.  
  10.         while(found == false && beginingElement <= lastElement)//As long as the value has not been found "AND" the begining subscript is not greater than the last in the array
  11.         {
  12.                 //adds subscript 0 and last then divides by 2.  Remainder is set to middle.
  13.                 middle = (beginingElement + lastElement) / 2;
  14.                 //if the middle of the array is equal to the value we are looking for then found is set to true
  15.                 //and the position is changed from -1 to whatever the subscript is for the middle variable.
  16.                 if(myArray[middle] == value)
  17.                 {
  18.                         found = true;
  19.                         position = middle;
  20.                 }
  21.                 //otherwise if the value we are looking for is less than the middle value
  22.                 //we take that middle value and go to the spot right before it and then make that the
  23.                 //new last element in turn cutting again the array in half.
  24.                 else if(myArray[middle] > value)
  25.                 {
  26.                         lastElement = middle - 1;
  27.                 }
  28.                 //otherwise if the value we are looking for is bigger than the middle then
  29.                 //we take the middle and go to the spot right after it and make that our new
  30.                 //starting spot again cutting the array in half.
  31.                 else
  32.                 {
  33.                         beginingElement = middle + 1;
  34.                 }
  35.         }
  36.         //lastly once we loop back to the top of the while loop and the found variable is now set to true
  37.         //the position element is stored and returned.
  38.         return position;
  39. }