Write a C program that uses non recursive function to search for a Key value in a given Sorted list of integers using binary search method
ALGORITHM:
BINARY SEARCH
1. 1. Start
2. 2. Read the value of n
3. 3. for i=1 to n increment in steps of 1
Read the value of ith element into array
4. 4. Read the element(x) to be searched
5. 5. search<--binary(a,n,x)
6. 6. if search equal to 0 goto step 7 otherwise goto step 8
7. 7. print unsuccessful search
8. 8. print successful search
9. 9. stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
int BinarySearching(int arr[20], int max, int element)
{
int low = 0, high = max - 1, middle;
while(low <= high)
{
middle = (low + high) / 2;
if(element > arr[middle])
low = middle + 1;
else if(element < arr[middle])
high = middle - 1;
else
return middle;
}
return -1;
}
void main()
{
int i,j,element,temp,n, arr[50], position;
//clrscr();
printf("\n Enter the N vaule of an array:");
scanf("%d", &n);
printf("\n Enter %d Elements in Array: \n",n);
for(i = 0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("\nthe array in sorted order:-\n");
for(i=0;i<n;i++)
printf("%d\t",arr[i]);
printf("\n Enter Element to Search:");
scanf("%d", &element);
position = BinarySearching(arr,n, element);
if(position == -1)
printf("Element %d Not Found\n", element);
else
printf("\n Element %d Found at Position %d\n",element,position + 1);
//getch();
}
OUTPUT:
Enter the N vaule of an array:6
Enter 6 Elements in Array:
45 67 13 24 78 10
the array in sorted order:-
10 13 24 45 67 78
Enter Element to Search:45
Element 45 Found at Position 4
Comments
Post a Comment