Advertisement
Maco153

Ahmed's Code

Nov 22nd, 2019
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. bool linear_search(int arr[],int n, int&counter)
  6.   {
  7.      
  8.     for (int i=0;i<50;i++)
  9.     {
  10.         counter++;
  11.         if (arr[i]==n){
  12.         return true;
  13.         break;
  14.    
  15.         }
  16.         }
  17.    
  18.     return false;
  19.   }
  20.    
  21. void binarySearch( int a[50], int first , int last,int key, bool& found, int &count2)
  22. {
  23.     int mid=0;
  24.      count2++;
  25.     if(first>last)
  26.     {
  27.         found = false;
  28.     }
  29.     else
  30.     {
  31.        
  32.         mid = (first+last)/2;
  33.         if (key==a[mid])
  34.         {
  35.             found= true;
  36.            
  37.         }
  38.         else if (key<a[mid])
  39.             binarySearch(a,first, mid-1,key,found,count2);
  40.          else if (key>a[mid])
  41.             binarySearch(a,mid+1,last ,key,found,count2);
  42.     }
  43. }
  44.  
  45. void bubblesort(int arr[], int length)
  46. {
  47.   for (int i=length-1;i>0;i--)
  48.     for (int j=0;j<i;j++)
  49.         if(arr [j]> arr[j+1])
  50.      {
  51.          int temp= arr[j+1];
  52.          arr[j+1]=arr[j];
  53.          arr[j]=temp;
  54.      }
  55. }
  56.  
  57. int main ()
  58. {
  59.  int arr[50]; int count2=0;
  60.  bool found;
  61.  int counter=0;
  62.     for (int i=0;i<50;i++)
  63.     arr[i]=rand();
  64.     bubblesort(arr,50);
  65.     for (int i=0;i<50;i++)
  66.     cout<<arr[i]<<endl;
  67.     int number;
  68.     cout<< "the number you need to search for : ";
  69.     cin>>number;
  70.     if (linear_search(arr,number,counter))
  71.     cout<< "using linear search the num exists after "<< counter<<endl;
  72.     else
  73.     cout<<"using linear search the number is not there after  "<< counter <<endl;
  74.     binarySearch( arr,0,49,number, found, count2 );
  75.    
  76.     if (found==true)
  77.     cout<<"using binary search the number is found after "<< count2<<endl;
  78.     else
  79.     cout<<"using binary search the number is not ther after "<<count2<<endl;
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement