Program 5
Implement
Binary Search algorithm to efficiently search for a specific
integer element in a
sorted array. Binary search works by repeatedly
dividing the search interval in half, comparing the target with the
middle element,
and eliminating half of the remaining elements with each iteration.
Algorithm
- Initialize: Start the program and declare variables
- Input Size: Read the number of elements in the array
- Input Array: Read n sorted integers into the array
- Input Search Key: Read the element to be searched
- Set Boundaries: Initialize low = 0, high = n-1, found = 0
- Binary Search Loop: While low ≤ high, calculate mid = (low + high) / 2
- Compare & Update: If arr[mid] == key, set found = 1; else update low or high
- Display Result: Show position if found, else show "not found" message
- Terminate: End the program
Flowchart
START
→
Input n, array
→
Input key
→
low=0, high=n-1
→
While low≤high
→
mid=(low+high)/2
→
Compare & Update
→
Display Result
→
STOP
Code
#include <stdio.h>
int main() {
int n, i, key, low, high, mid;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d sorted elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Enter element to search: ");
scanf("%d", &key);
low = 0;
high = n - 1;
int found = 0;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key) {
printf("Element %d found at position %d\n", key, mid + 1);
found = 1;
break;
}
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
if (!found)
printf("Element %d not found in the array.\n", key);
return 0;
}
Replay !
Share Your Thoughts