Wednesday, 10 September 2014

Binary search in C Language using arrays with example program

 BINARY SEARCH IN C

Binary search in C using arrays: An example C program is available here. Given source code is based on basic search operations by using the advantage of arrays. Sample code is also given below for your reference.

Binary search in C program by arrays is used to search the value in a sorted array. This C code is using some sorting techniques and using binary search also. We can find the location of an element, if it is present in the array value else it will display like not found.

//Header files
 #include<stdio.h>
 #include<conio.h>
 main()
 {
//Program variables
 int lw=0,hh=7,md,ky,f=0;
 int b[7]={20,4,6,1,18,17,24};
 printf("Enter the element to be searched"); //Display function
 scanf("%d",&ky); //Getting input function
 while(lw<hh) && (f!=1)) //Unconditional statement
 {
 mid=(lw+hh)/2;
 if(ky<b[md]) //Conditional statement
 hh=md-1;
// printf("element is found at %d location",md);
  if(ky>b[md])
  lw=md+1;
 // printf("element is found at %d location",md);
if(ky==b[md])
printf("Element is found");
else
printf("Element is not found");
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.