Skip to content

Commit 7320ee1

Browse files
authored
Merge pull request #34 from rahullo/master
Adding binary search algorithm in cpp.
2 parents 7163983 + 75be8c7 commit 7320ee1

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Diff for: SearchingAlgorithms/binarySearch/binarySearch.cpp

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// This is binary search algorithm in cpp. This algorithm is implemented in both way, using simple
2+
// while loop and recursion.
3+
4+
#include<iostream>
5+
#include<stdio.h>
6+
7+
using namespace std;
8+
9+
10+
//This function is implemented using recursion..
11+
void binarySearch(int arr[], int low, int high, int num){
12+
int mid = (low+high)/2;
13+
if(arr[mid] == num){
14+
cout<<num<<" is found at index "<<mid<<endl;
15+
return;
16+
}
17+
if(arr[mid] < num){
18+
binarySearch(arr, mid+1, high, num);
19+
}
20+
else if(arr[mid] > num){
21+
binarySearch(arr, 0, mid-1, num);
22+
}
23+
}
24+
25+
// This function is implemented using while loop.
26+
// Binary Search in C++
27+
void binarySearch2(int arr[], int low, int high, int num) {
28+
29+
// Repeat until the pointers low and high meet each other
30+
while (low <= high) {
31+
int mid = low + (high - low) / 2;
32+
33+
if (arr[mid] == num){
34+
cout<<num<<" is found at index "<<mid<<endl;
35+
break;
36+
}
37+
38+
if (arr[mid] < num){
39+
low = mid + 1;
40+
}
41+
42+
else{
43+
high = mid - 1;
44+
}
45+
}
46+
47+
}
48+
49+
int main()
50+
{
51+
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 14, 15, 18};
52+
int len = sizeof(arr)/sizeof(arr[0]);
53+
binarySearch(arr, 0, len-1, 18);
54+
binarySearch2(arr, 0, len-1, 15);
55+
return 0;
56+
}

0 commit comments

Comments
 (0)