Sunday, 6 May 2012

Binary Searching in C


#include <cstdlib>
#include <ctime>
#include <iostream>


using namespace std;


int main()
  {
  int left;
  int right;
  int time2stop;
  int half;
  int findme;
  const int MAXSIZE = 5;
  int myArray[MAXSIZE+1];
  srand((unsigned)time(0));
  myArray[1] = (rand()%10)+1;
  cout << myArray[1] << "  ";


  for(int i=2; i<MAXSIZE+1; i++)
    {
    myArray[i] = myArray[i-1] + (rand()%10)+1;
    cout << myArray[i] << "  ";
    }
  cout << "\n";


  cout << "Which number do you want to find: ";
  cin >> findme;


  left = 1;
  right = MAXSIZE;
  time2stop = 0;
  while (time2stop == 0)
    {
      half = int((left+right)/2);
      if (findme<myArray[half])
      {
        right = half - 1;
      }
      else
      {
        left = half + 1;
      }
      if ((findme == myArray[half]) || (left > right))
      {
      time2stop = 1;
      }
      }


  if (findme == myArray[half])
    {
     cout << "Found it in location " << half << "\n";
   }
  else
    {
     cout << "The number you want is not in the list.";
   }
   cout << "\nPress ENTER to continue..." << endl;
   getchar();
  }

No comments:

Post a Comment