reellearning

Linear vs. Binary Search

Jul 10th, 2012
1,741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. /*
  2.  * linearvsbinary.cpp
  3.  *
  4.  *  Created on: July 10, 2012
  5.  *      Author: Derek
  6.  *
  7.  *  Comparison of linear and binary search algorithms
  8.  */
  9.  
  10. #include <iostream>
  11. using namespace std;
  12.  
  13. void linearSearch(int array[], int size, int searchValue)
  14. {
  15.     int count = 0;
  16.  
  17.     for(int i = 0; i < size; i++)
  18.     {
  19.         count++;
  20.         if (searchValue == array[i])
  21.         {
  22.             break;
  23.         }
  24.  
  25.     }
  26.  
  27.     cout << "Linear Search comparisons: " << count << endl;
  28.  
  29. }
  30.  
  31. void binarySearch(int array[], int size, int searchValue)
  32. {
  33.     int low = 0;
  34.     int high = size - 1;
  35.     int mid;
  36.     int count = 0;
  37.  
  38.     while (low <= high)
  39.     {
  40.         mid = (low + high) / 2;
  41.  
  42.         count++;
  43.         if(searchValue == array[mid])
  44.         {
  45.             break;
  46.         }
  47.         else if (searchValue > array[mid])
  48.         {
  49.             low = mid + 1;
  50.         }
  51.         else
  52.         {
  53.             high = mid - 1;
  54.         }
  55.     }
  56.  
  57.  
  58.     cout << "Binary Search comparisons: " << count << endl;
  59.  
  60. }
  61.  
  62. void populateArray(int array[], int size)
  63. {
  64.     for(int i = 1; i <= size; i++)
  65.     {
  66.         array[i - 1] = i;
  67.     }
  68. }
  69.  
  70. int main()
  71. {
  72.     int size;
  73.     int userValue;
  74.     char input;
  75.  
  76.     do
  77.     {
  78.  
  79.         cout << "Enter an int for the size of the array:" << endl;
  80.         cin >> size;
  81.  
  82.         int a[size];
  83.  
  84.         cout << "Enter an integer between 1 and " << size << " to search for in the array." << endl;
  85.         cin >> userValue;
  86.  
  87.         populateArray(a, size);
  88.  
  89.         linearSearch(a, size, userValue);
  90.         binarySearch(a, size, userValue);
  91.  
  92.         cout << "Press 'y' and enter to run again or just enter to quit";
  93.         cin.sync();
  94.         cin.get(input);
  95.  
  96.     }while(input == 'y');
  97. }
Advertisement
Add Comment
Please, Sign In to add comment