NOTE** BINARY SEARCH WORKS FOR ONLY SORTED ARRAY
| 118 | |
| 119 | //***NOTE** BINARY SEARCH WORKS FOR ONLY SORTED ARRAY |
| 120 | int binarySearch(int arr[], int key, int size) |
| 121 | { |
| 122 | // Example: 1 2 3 4 5 |
| 123 | // low mid high |
| 124 | |
| 125 | // mid= 0 + 4 / 2 = 2 i.e element at middle is at index 2 |
| 126 | int low = 0; |
| 127 | int mid; |
| 128 | int high = size - 1; |
| 129 | // WHILE loop to check that array is not empty i.e low should not be greater than high |
| 130 | while (low <= high) |
| 131 | { |
| 132 | mid = (low + high) / 2; |
| 133 | // If element is found at certain index return value of mid |
| 134 | if (arr[mid] == key) |
| 135 | { |
| 136 | cout << "The element " << key << " is found at index " << mid << endl; |
| 137 | return mid; |
| 138 | } |
| 139 | // If element is bigger than middle element then check from middle to high |
| 140 | else if (arr[mid] < key) |
| 141 | { |
| 142 | low = mid + 1; |
| 143 | } |
| 144 | // If element is smaller than middle element then check from low to middle |
| 145 | else |
| 146 | { |
| 147 | high = mid - 1; |
| 148 | } |
| 149 | } |
| 150 | cout << "Element Not Found!!" << endl; |
| 151 | } |
| 152 | |
| 153 | //------------------------------------------------------------------------------------------------------------------------------------------- |
| 154 |