Advertisement
Maco153

Random Number generator and search

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