Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Example program
- #include <iostream>
- #include <string>
- using namespace std;
- #define N 10
- int linear_search(int arr[], int n, int target)
- {
- for (int i = 0; i < n; i++)
- {
- cout<<target<<" and "<<arr[i]<<endl;
- if (arr[i] == target)
- {
- cout<<"index of element is "<<i;
- return i;
- }
- }
- }
- int binary_search(int arr[], int n, int target, int l, int r)
- {
- int mid;
- while (l <= r)
- {
- mid = (l + r) / 2;
- cout<<"middle element is "<<arr[mid]<<endl;
- cout<<target<<" and "<<arr[mid]<<endl;
- if(arr[mid] != target)
- {
- if (arr[mid] > target)
- {
- cout<<arr[mid]<<" > "<<target<<" then "<<endl;
- r = mid - 1;
- }
- if (arr[mid] < target)
- {
- cout<<arr[mid]<<" < "<<target<<" then "<<endl;
- l = mid + 1;
- }
- }
- if (arr[mid] == target)
- {
- cout<<"Index of element is "<<mid;
- return mid;
- }
- }
- }
- int doubling_search(int arr[], int n, int target)
- {
- int pos = 1;
- while (arr[pos] < target)
- pos *= 2;
- int left = pos/2;
- binary_search(arr,n,target,left,pos);
- }
- int main()
- {
- int array[N];
- int n, target;
- cin >> n;
- cin >> target;
- for (int i = 0; i < n; i++)
- cin>>array[i];
- cout<<"Linear: "<<endl;
- linear_search(array,n,target);
- cout<<"Binary: "<<endl;
- int begin = 0;
- int end = n - 1;
- binary_search(array,n,target,begin,end);
- cout<<"Doubling: "<<endl;
- doubling_search(arr,n,target);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement