Advertisement
UntitledPotato

binarySearch

Sep 18th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6.     int size , temp , i , j ;
  7.     cout << "Enter the amount of numbers you want to enter : " ;
  8.     cin >> size ;
  9.     int array[size];
  10.     int key , mid , first = 0 , last = size-1 , found = 0 , index ;
  11.    
  12.     for (i = 0 ; i < size ; i++)
  13.     {
  14.         cout << "Enter a number : " ;
  15.         cin >> array[i];
  16.     }
  17.    
  18.     for (i = 0 ; i < size ; i++)
  19.     {
  20.         for (j = 0 ; j < size-i-1 ; j++)
  21.         {
  22.             if (array[j] > array[j+1])
  23.             {
  24.                 temp = array[j];
  25.                 array[j] = array[j+1];
  26.                 array[j+1] = temp;
  27.             }
  28.         }
  29.     }
  30.  
  31.     cout << "Enter the number you're looking for : " ;
  32.     cin >> key ;
  33.    
  34.     while (first <= last && found == 0/*!found*/)
  35.     {
  36.         mid = (first+last)/2;
  37.         if (key == array[mid])
  38.         {
  39.             found = 1;
  40.             index = mid;
  41.         } else if (key > array[mid]) {
  42.             first = mid+1;
  43.         } else {
  44.             last = mid-1;
  45.         }
  46.     }
  47.    
  48.     if (found == 1)
  49.     {
  50.         cout << "We found the number you're looking for.\nIt's in room number." << index+1 << endl;
  51.     } else {
  52.         cout << "Unfortunately,we couldn't find the number for you." << endl;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement