C++ Program to Implement Binary Search using Iteration

This is a C++ Program to implement Binary Search Algorithm.

Problem Description

We have to write a C++ Program which either finds the position of an element in an array or detects the presence of an element in an array using Binary Search Algorithm.

Expected Input and Output

Case 1. Average Case: When the element to be searched for is any random element from the array.

If the input array is {1, 2, 3, 4, 5, 6}
and the element to be searched for is 6,
then the output will be SEARCH SUCCESSFUL.

Average case time complexity: O(log n)

Case 2. Best case: When the element to be searched for is the middle element of the array.

advertisement
advertisement
If the input array is {-3, 31, 66}
and the element to be searched is 31,
then the output will be SEARCH SUCCESSFUL.

Best case time complexity: O(1)

Case 3. Worst Case: When the element searched for is absent and it is either smaller or greater than all the elements.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
If the input array is {1, 1, 3, 6, 9}
and the element to be searched for is 10,
then the output will be SEARCH FAILED

Worst case time complexity: O(log n)

Problem Solution

We will be having an array of numbers, we just need to find out the position of an element in the array if it is present. It can be done using Linear Search but it takes up a lot of time, so we need a better searching algorithm that performs the same task but in less time in comparison to Linear Search. In worst case Linear Search takes O(n) time, but Binary Search takes O(log n) time.

Program/Source Code

Here is source code of the C++ Program to find the position of an element requested by the user using Binary Search Algorithm using iteration. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.

advertisement
  1. /*
  2.  * C++ program to accept N numbers sorted in ascending order
  3.  * and to search for a given number using Binary Search.
  4.  * Report success or failure.
  5.  */
  6. #include <iostream>
  7. using namespace std;
  8. class BS
  9. {
  10. public:
  11.     /*
  12.      * Binary Search function
  13.      */
  14.     void BinarySearch(int array[], int keynum, int num)
  15.     {
  16.         int low = 1;
  17.         int high = num;
  18.         int mid;
  19.     do
  20.     {
  21.         mid = (low + high) / 2;
  22.         if (keynum < array[mid])
  23.         {
  24.             high = mid - 1;
  25.         }
  26.    	else if (keynum > array[mid])
  27.         {
  28.             low = mid + 1;
  29.         }
  30. 	}
  31. 	while (keynum != array[mid] && low <= high);
  32.         if (keynum == array[mid])
  33.         {
  34.             cout<<"SEARCH SUCCESSFUL \n";
  35.         }
  36.         else
  37.         {
  38.             cout<<"SEARCH FAILED \n";
  39.         }
  40.     }
  41. };
  42. int main()
  43. {
  44.     int array[10];
  45.     int i, j, num, temp, keynum;
  46.     int low, mid, high;
  47.     cout<<"Enter the value of num \n";
  48.     cin>>num;
  49.     cout<<"Enter the elements one by one \n";
  50.     for (i = 0; i < num; i++)
  51.     {
  52.         cin>>array[i];
  53.     }
  54.     /*
  55.      * Bubble sort
  56.      */
  57.     for (i = 0; i < num; i++)
  58.     {
  59.         for (j = 0; j < (num - i - 1); j++)
  60.         {
  61.             if (array[j] > array[j + 1])
  62.             {
  63.                 temp = array[j];
  64.                 array[j] = array[j + 1];
  65.                 array[j + 1] = temp;
  66.             }
  67.         }
  68.     }
  69.     cout<<"Enter the element to be searched \n";
  70.     cin>>keynum;
  71.     // Binary searching begins
  72.     BS b1;
  73.     b1.BinarySearch(array, keynum, num);
  74.     return 0;
  75. }
Program Explanation

1. Here in this program we have first requested the array of numbers and the value to be searched from the user.
2. Since binary search is applied upon a sorted array we have created a separate bubble sort function to sort the array before searching.
3. After sorting the array we have passed the array to the function called BinarySearch(array, keynum, num) having array, key and the size of array as its parameters.
4. In BinarySearch(array, keynum, num) we first find the middle index of the array, and then compare the key with the middle element of array i.e. array[middle].
5. If key is less than the middle element of array we divide the array in to two halves i.e. low to mid-1 and (mid+1) to high, where mid is the middle index, low is the starting and high is the ending index of the array. After dividing the array we start searching in the left half of the array i.e. low to mid-1.
6. If the key is greater than the middle element then we search in the right half of the array i.e mid+1 to high.
7. In each iteration we divide the array until it has only 1 element left.
8. If we are able to find the element we print “SEARCH SUCCESSFUL” otherwise we print “SEARCH FAILED”.

Runtime Test Cases
1. Enter the value of num
   6
   Enter the elements one by one
   1 2 3 4 5 6
   Enter the element to be searched
   6
   SEARCH SUCCESSFUL
 
2. Enter the value of num
   3
   Enter the elements one by one
   -3 31 66
   Enter the element to be searched
   31
   SEARCH SUCCESSFUL
 
3. Enter the value of num
   5
   Enter the elements one by one
   1 1 3 6 9
   Enter the element to be searched 
   10
   SEARCH FAILED

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.

advertisement

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.