Write a program in C to search an element in an array using binary search.
To search for an element in an array using Binary Search the array should be sorted.
Code:
#include <stdio.h>
int main()
{
int i,first,last,middle,n,element,array[100];
// read number of elements
printf("Enter number of elements to enter in the array (max 100):");
scanf("%d",&n);
// input elements in the array
printf("Enter %d elements one by one in ascending order:\n",n);
for(i=0;i<n;i++)
scanf("%d",&array[i]);
// read element to search for
printf("Enter the element to be searched in the array:");
scanf("%d",&element);
// algorithm for binary search
first = 0;
last = n-1;
middle = (first+last)/2;
while(first<=last){
if(element > array[middle])
first = middle+1;
else if(element < array[middle])
last = middle-1;
else{
printf("%d found at position %d",element,middle+1);
break;
}
middle = (first+last)/2;
}
if(first>last)
printf("%d not found in the array!",element);
return 0;
}
To search for an element in an array using Binary Search the array should be sorted.
Code:
#include <stdio.h>
int main()
{
int i,first,last,middle,n,element,array[100];
// read number of elements
printf("Enter number of elements to enter in the array (max 100):");
scanf("%d",&n);
// input elements in the array
printf("Enter %d elements one by one in ascending order:\n",n);
for(i=0;i<n;i++)
scanf("%d",&array[i]);
// read element to search for
printf("Enter the element to be searched in the array:");
scanf("%d",&element);
// algorithm for binary search
first = 0;
last = n-1;
middle = (first+last)/2;
while(first<=last){
if(element > array[middle])
first = middle+1;
else if(element < array[middle])
last = middle-1;
else{
printf("%d found at position %d",element,middle+1);
break;
}
middle = (first+last)/2;
}
if(first>last)
printf("%d not found in the array!",element);
return 0;
}
No comments:
Post a Comment