1- #include < iostream>
2- using namespace std ;
1+ #include < stdio.h>
32
3+ /*
4+ ======================================================
5+ Binary Search Algorithm
6+ ======================================================
7+ Description:
8+ Binary Search is an efficient algorithm to find the position of a target value
9+ in a sorted array. It repeatedly divides the search interval in half.
410
11+ Key Idea:
12+ 1. Start with the entire array as the search interval.
13+ 2. Find the middle element.
14+ 3. If the middle element is equal to the target, return its index.
15+ 4. If the target is smaller, search the left half.
16+ 5. If the target is larger, search the right half.
17+ 6. Repeat until the target is found or interval is empty.
518
19+ Time Complexity: O(log n)
20+ Space Complexity: O(1) for iterative implementation
21+ ======================================================
22+ */
623
7- int binarysearch (int arr[], int size, int key){
8- int s = 0 ; // startingpoint
9- int e = size-1 ; // ending point
10- while (s<size){
11- int mid = (s+(e-1 ))/2 ;
12- if (arr[mid]==key){
13- return mid;
24+ // Iterative Binary Search function
25+ int binarySearch (int arr[], int size, int target) {
26+ int left = 0 ;
27+ int right = size - 1 ;
28+
29+ while (left <= right) {
30+ int mid = left + (right - left) / 2 ; // prevents overflow
31+
32+ if (arr[mid] == target) {
33+ return mid; // Target found
1434 }
15- else if (arr[mid] > key) {
16- e = mid- 1 ;
35+ else if (arr[mid] < target) {
36+ left = mid + 1 ; // Search in right half
1737 }
18- else {
19- s = mid+ 1 ;
38+ else {
39+ right = mid - 1 ; // Search in left half
2040 }
2141 }
22- // if not work then we ll return -1
23- return -1 ;
24- }
25-
26-
27-
2842
43+ return -1 ; // Target not found
44+ }
2945
46+ int main () {
47+ int n, target;
3048
49+ // Input the size of the array
50+ printf (" Enter size of array: " );
51+ scanf (" %d" , &n);
3152
53+ int arr[n];
54+ printf (" Enter %d elements in sorted order: " , n);
55+ for (int i = 0 ; i < n; i++) {
56+ scanf (" %d" , &arr[i]);
57+ }
3258
33- int main (){
59+ // Input the target value
60+ printf (" Enter the target value: " );
61+ scanf (" %d" , &target);
3462
35- int size;
36- cout<<" enter the size of the array : " ;
37- cin>>size;
38- int key;
39- cout<<" enter the key : " ;
40- cin>>key;
63+ // Call Binary Search
64+ int result = binarySearch (arr, n, target);
4165
42- int arr[size];
43- cout<<" Enter the elements of array : " <<endl;
44- for (int i = 0 ; i<size; i++){
45- cin>>arr[i];
46- }
47- int result = binarysearch (arr,size,key);
48- if (result == -1 ){
49- cout<<" Element is not present in the array" <<endl;
50- }
51- else {
52- cout<<" Element is present at index " <<result<<endl;
66+ if (result != -1 ) {
67+ printf (" Target %d found at index %d.\n " , target, result);
68+ } else {
69+ printf (" Target %d not found in the array.\n " , target);
5370 }
5471
5572 return 0 ;
56- }
73+ }
0 commit comments