Advertisement
skb50bd

Linear Search and Binary Search

Mar 29th, 2016
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void swap(int &a, int &b) {
  5.     a = a + b;
  6.     b = a - b;
  7.     a = a - b;
  8. }
  9.  
  10. int main() {
  11.     int n;
  12.     cout << "Size of the Array: ";
  13.     cin >> n;
  14.  
  15.     int arr[n];
  16.     int SearchItem;
  17.     bool found = false;
  18.     cout << "Enter " << n << " Elements: ";
  19.     for(int i = 0; i < n; i++)
  20.         cin >> arr[i];
  21.  
  22. //    Linear Search
  23.     cout << "Enter the value to find (Linear Search): ";
  24.     cin >> SearchItem;
  25.     for(int i = 0; i < n; i++)
  26.         if(arr[i] == SearchItem) {
  27.         cout << SearchItem << " Found in Location: " << i << endl << endl;
  28.         found = true;
  29.         break;
  30.     }
  31.     if(found == false)
  32.         cout << SearchItem << " Not Found" << endl << endl;
  33.  
  34.  
  35.  
  36.     //Binary Search
  37.     for(int i = 0; i < n - 1; i++)  //FOR SORTING (SELECTION)
  38.         for(int j = i + 1; j < n; j++)
  39.             if(arr[i] > arr[j])
  40.                 swap(arr[i], arr[j]);
  41.  
  42.  
  43.     cout << "Enter the value to find (Binary Search): ";
  44.     cin >> SearchItem;
  45.  
  46.     int i = 0, j = n, m;
  47.     found = false;
  48.     while(true) {
  49.         m = (i + j) / 2;
  50.         if(arr[m] == SearchItem){
  51.             cout << SearchItem << " Found" << endl;
  52.             found = true;
  53.             break;
  54.         }
  55.         else if(i == m)
  56.             break;
  57.         else if(arr[m] < SearchItem)
  58.             i = m + 1;
  59.         else
  60.             j = m;
  61.     }
  62.     if(found == false)
  63.         cout << SearchItem << " Not Found" << endl << endl;
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement