BINARY SEARCH
AIM :
To learn about binary search technique and implement it in C programming language.
ALGORITHM :
Step 1: [INITIALIZE] SET BEG = 0
END=n-1, POS=-1
Step 2: Repeat Steps 3 and 4 while BEG <=END
Step 3: SET MID =(BEG+END)/2
Step 4: IF A[MID] = VAL
SET POS= MID
PRINT POS
Go to Step 6
ELSE IF A[MID] > VAL
SET END=MID-1
ELSE
SET BEG= MID+1
[END OF IF]
[END OF LOOP]
Step 5: IF POS=-1
PRINT "VALUE IS NOT PRESENT IN THE ARRAY"
[END OF IF]
Step 6: EXIT
SOURCE CODE:
#include <conio.h>
#include <stdio.h>
int Binarysearch(int[], int, int);
void main() {
int x[20], i, n, p, key;
printf("\nEnter the number of elements: ");
scanf("%d", &n);
printf("\nEnter %d elements in ascending order: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &x[i]);
}
printf("\nEnter the element to search: ");
scanf("%d", &key);
p = Binarysearch(x, n, key);
if (p == -1) {
printf("\nSearch unsuccessful: %d not found in the array.\n", key);
} else {
printf("\nSearch successful: %d is found at location %d.\n", key, p + 1);
}
}
int Binarysearch(int a[], int n, int k) {
int lo = 0, hi = n - 1, mid;
printf("\n--- Binary Search Steps ---\n");
while (lo <= hi) {
mid = (lo + hi) / 2;
printf("\nChecking middle element: a[%d] = %d", mid + 1, a[mid]);
if (k == a[mid]) {
printf("\nMatch found! a[%d] = %d matches %d.\n", mid + 1, a[mid], k);
return mid;
} else if (k < a[mid]) {
printf("\nNo match. %d < %d, so we move to the left side.", k, a[mid]);
hi = mid - 1;
} else {
printf("\nNo match. %d > %d, so we move to the right side.", k, a[mid]);
lo = mid + 1;
}
}
printf("\nElement %d not found after searching all possible elements.\n", k);
return -1;
}
INPUT AND OUTPUT:
RESULT:
The binary search algorithm has been implemented in C and tested with sample input for correct
functioning.