Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. //
  2. //
  3. //
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. int linearSearch(int[], int, int, int&);
  8. int binarySearch(int[], int, int, int&);
  9.  
  10. int main(){
  11.    
  12.     const int SIZE = 20;
  13.     int array[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  14.                  11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
  15.    
  16.     int num,
  17.         binresult,
  18.         linresult,
  19.         value,
  20.         result1 = 0,
  21.         result2 = 0;
  22.    
  23.     cout << "Enter a number to search for: " << endl;
  24.     cin >> num;
  25.    
  26.     linresult = linearSearch( int list[], SIZE, value, result1);
  27.     binresult = binarySearch(array, SIZE, value, result2);
  28.    
  29.    
  30.     cout << "Linear search: " << linearSearch << endl;
  31.     cout << "Binary search: " << binarySearch << endl;
  32.    
  33.     return 0;
  34. }
  35.  
  36. int linearSearch(int list[], int SIZE, int value, int& result1){
  37.    
  38.     int index = 0;
  39.     int position = -1;
  40.     bool found = false;
  41.    
  42.     while (index < SIZE && !found){
  43.        
  44.         if (list[index] == value){
  45.            
  46.             found = true;
  47.             position = index;
  48.         }
  49.         index++;
  50.        
  51.         if (position == -1)
  52.             result1++;
  53.     }
  54.     return position;
  55. }
  56.  
  57. int binarySearch(int array[], int SIZE, int value, int& result2){
  58.    
  59.     int first = 0,
  60.         last = SIZE - 1,
  61.         middle,
  62.         position = -1;
  63.     bool found = false;
  64.    
  65.     while (!found && first <= last){
  66.        
  67.         middle = (first + last) / 2;
  68.         if (array[middle] == value)
  69.         {
  70.             found = true;
  71.             position = middle;
  72.         }
  73.         else if (array[middle] == value)
  74.             last = middle - 1;
  75.         else
  76.             first = middle + 1;
  77.            
  78.         if (position == -1)
  79.             result2++;
  80.     }
  81.     return position;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement