Advertisement
Guest User

Searchs

a guest
Oct 14th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. // Example program
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. #define N 10
  6. int linear_search(int arr[], int n, int target)
  7. {    
  8.     for (int i = 0; i < n; i++)
  9.     {
  10.         cout<<target<<" and "<<arr[i]<<endl;
  11.         if (arr[i] == target)
  12.         {
  13.             cout<<"index of element is "<<i;
  14.             return i;
  15.         }
  16.     }
  17. }
  18.  
  19.  
  20. int binary_search(int arr[], int n, int target, int l, int r)
  21. {
  22.     int mid;
  23.     while (l <= r)
  24.     {
  25.         mid = (l + r) / 2;
  26.         cout<<"middle element is "<<arr[mid]<<endl;
  27.         cout<<target<<" and "<<arr[mid]<<endl;
  28.         if(arr[mid] != target)
  29.         {
  30.             if (arr[mid] > target)
  31.             {
  32.                 cout<<arr[mid]<<" > "<<target<<" then "<<endl;
  33.                 r = mid - 1;
  34.             }
  35.             if (arr[mid] < target)
  36.             {
  37.                 cout<<arr[mid]<<" < "<<target<<" then "<<endl;  
  38.                 l = mid + 1;
  39.             }
  40.         }
  41.         if (arr[mid] == target)
  42.         {
  43.             cout<<"Index of element is "<<mid;
  44.             return mid;
  45.         }
  46.     }
  47. }
  48.  
  49. int doubling_search(int arr[], int n, int target)
  50. {
  51.     int pos = 1;
  52.     while (arr[pos] < target)
  53.         pos *= 2;
  54.     int left = pos/2;
  55.     binary_search(arr,n,target,left,pos);
  56. }
  57.  
  58. int main()
  59. {
  60.     int array[N];
  61.     int n, target;
  62.     cin >> n;
  63.     cin >> target;
  64.     for (int i = 0; i < n; i++)
  65.         cin>>array[i];
  66.     cout<<"Linear: "<<endl;
  67.     linear_search(array,n,target);
  68.     cout<<"Binary: "<<endl;
  69.     int begin = 0;
  70.     int end = n - 1;
  71.     binary_search(array,n,target,begin,end);
  72.     cout<<"Doubling: "<<endl;
  73.     doubling_search(arr,n,target);
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement