Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- bool linear_search(int arr[],int n, int&counter)
- {
- for (int i=0;i<50;i++)
- {
- counter++;
- if (arr[i]==n){
- return true;
- break;
- }
- }
- return false;
- }
- void binarySearch( int a[50], int first , int last,int key, bool& found, int &count2)
- {
- int mid=0;
- count2++;
- if(first>last)
- {
- found = false;
- }
- else
- {
- mid = (first+last)/2;
- if (key==a[mid])
- {
- found= true;
- }
- else if (key<a[mid])
- binarySearch(a,first, mid-1,key,found,count2);
- else if (key>a[mid])
- binarySearch(a,mid+1,last ,key,found,count2);
- }
- }
- void bubblesort(int arr[], int length)
- {
- for (int i=length-1;i>0;i--)
- for (int j=0;j<i;j++)
- if(arr [j]> arr[j+1])
- {
- int temp= arr[j+1];
- arr[j+1]=arr[j];
- arr[j]=temp;
- }
- }
- int main ()
- {
- int arr[50]; int count2=0;
- bool found;
- int counter=0;
- for (int i=0;i<50;i++)
- arr[i]=rand();
- bubblesort(arr,50);
- for (int i=0;i<50;i++)
- cout<<arr[i]<<endl;
- int number;
- cout<< "the number you need to search for : ";
- cin>>number;
- if (linear_search(arr,number,counter))
- cout<< "using linear search the num exists after "<< counter<<endl;
- else
- cout<<"using linear search the number is not there after "<< counter <<endl;
- binarySearch( arr,0,49,number, found, count2 );
- if (found==true)
- cout<<"using binary search the number is found after "<< count2<<endl;
- else
- cout<<"using binary search the number is not ther after "<<count2<<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement