
Binary Search in C
Algorithm
Input: Input the size, elements of an array and element to search.
Output: Displays the index of the element if present
- Start
- Read the size of the array and store it in a variable say n
- Read the elements of the array
- Read the element to be searched
- i=0, j=0
- while i<n
6.1 while j< ( n-i-1)
6.1.1 if a[ j ] > a [ j+1 ]
6.1.1.1 temp = a [ j ]
6.1.1.2 a[ j ] = a [ j+1 ]
6.1.1.3 a [ j+1 ] = temp - left = 0, right= n
- while left <= right
8.1 mid = (left+right)/2
8.2 if search = = a [ mid ]
8.2.1 Print "The element can be found at" + mid
8.2.2 exit
8.3 else if search < a [ mid ]
8.3.1 right = mid-1
8.4 else
8.4.1 left =mid+1 - return Print "Element not present in the inputed array"
- stop
C Program
# include <stdio.h>
int main ( ) {
int n,temp;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a [n];
printf("Enter the elements of the array one by one \n");
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
//Sorting logic
for (int i = 0; i < n; i++) {
for (int j = 0; j < (n-i-1); j++) {
if ( a[j] > a [j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}}
}
// Binary Search Logic
int left = 0,right = n,search,found=0;
printf("Enter a number to search: ");
scanf("%d",&search);
while(left<=right) {
int mid=(left+right)/2;
if (search == a[mid]){
printf("The element can be found at index %d",mid);
exit(0);
} else if (search < a[mid]) {
right=mid-1;
} else {
left=mid+1;
}
}
return printf("Element not present in the inputed array");
}
Output
Enter the size of array:5
Enter the elements in the array:
5
9
7
2
1
Enter a number to search:1
The element can be found at index 0
Comments