fork download
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include <iomanip>
  4.  
  5. using namespace std;
  6.  
  7. int binarySearch(const int [], int, int, int, int ); // function prototype
  8.  
  9. int main()
  10. {
  11. const int arraySize = 10;
  12. int arr[ arraySize ];
  13. int key;
  14.  
  15. for( int i = 0; i < arraySize; i++) // generate data for array
  16. arr[i] = 2*i;
  17.  
  18. cout << "The array being searched is: " << endl;
  19.  
  20. for (int j = 0; j<arraySize; j++) // print subscript index of the array
  21. {
  22. cout << setw(5) << j << " ";
  23. }
  24.  
  25. cout << endl;
  26.  
  27. for (int z = 0; z<arraySize; z++) // print elements of the array below index
  28. {
  29. cout << setw(5) << arr[z] << " ";
  30. }
  31.  
  32. cout << "\n" <<"Enter value you want to search in array " << endl;
  33. cin >> key;
  34.  
  35. int result = binarySearch(arr, key, 0, arraySize, arraySize); // function call
  36.  
  37. if (result == 1) // print result of search
  38. cout << "Key is found " << endl;
  39. else
  40. cout << "Key not found " << endl;
  41.  
  42. return 0;
  43. } // end main function
  44.  
  45. int binarySearch(const int a[], int searchKey, int low, int high, int length)
  46. {
  47. int middle;
  48.  
  49. while (low <= high){
  50.  
  51. middle = (low + high) / 2;
  52.  
  53. if (searchKey == a[middle]) // search value found in the array, we have a match
  54. {
  55. return 1;
  56. break;
  57. }
  58.  
  59. else
  60. {
  61. if( searchKey < a[middle] ) // if search value less than middle element
  62. high = middle - 1; // set a new high element
  63. else
  64. low = middle + 1; // otherwise search high end of the array
  65. }
  66. }
  67. return -1;
  68. }
Success #stdin #stdout 0s 3464KB
stdin
21
stdout
The array being searched is: 
    0     1     2     3     4     5     6     7     8     9 
    0     2     4     6     8    10    12    14    16    18 
Enter value you want to search in array 
Key not found