File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+
3
+ using namespace std ;
4
+
5
+ int array[15 ], i, x, n;
6
+
7
+ int BinarySearch (int low, int high)
8
+ {
9
+ while (low<=high)
10
+ {
11
+
12
+
13
+
14
+ int mid=(low+high)/2 ;
15
+
16
+ if (array[mid]==x)
17
+ {
18
+ return mid;
19
+ }
20
+ else if (array[mid] >x)
21
+ {
22
+ high=mid-1 ;
23
+ }
24
+ else
25
+ {
26
+ low=mid+1 ;
27
+ }
28
+ return -1 ;
29
+ }
30
+ }
31
+
32
+
33
+ int main () {
34
+ cout << " Input the size of array: " ;
35
+ cin >> n;
36
+
37
+ cout << " Input the values of the array (in sorted order): " ;
38
+ for (i = 0 ; i < n; i++) {
39
+ cin >> array[i];
40
+ }
41
+
42
+ cout << " Input the value you want to search: " ;
43
+ cin >> x;
44
+
45
+ // Call the function
46
+ int result = BinarySearch (0 , n - 1 );
47
+ if (result == -1 ) {
48
+ cout << " The value is not found in the array." ;
49
+ } else {
50
+ cout << " The value is found at index: " << result;
51
+ }
52
+
53
+ return 0 ;
54
+ }
You can’t perform that action at this time.
0 commit comments