Binary Search

Google Advertisements

Prev Tutorial Next Tutorial

Binary Search in C

This searching technique is applicable only for sorted array, but this searching technique is faster than linear search.

Steps for binary search

You need to first sort elements of array if it is not in sorted order, because binary search is only application on sorted element.

binary search
  • First find the middle element of the array.
  • Compare the middle element with the item. After this step there are three cases;
  1. If middle element is a desired item then search is successful
  2. If middle element is less than desired item then search only the first half of the array.
  3. If middle element is grater than the desired item search in the second half of the array.
  4. Repeat same steps until element is found.
binary search step

Binary Search Program in C

	
#include<stdio.h>
#include<conio.h>
#include<dos.h>

void main()
{
int i, first, last, middle, n, search, array[100];
clrscr();
printf("Enter size of array to enter elements\n");
scanf("%d",&n);

printf("Enter %d elements\n", n);

for (i = 0; i < n; i++)
scanf("%d",&array[i]);

printf("Enter element to find\n");
scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list.\n", search);
getch();
}
binary search
Prev Tutorial Next Tutorial

Google Advertisements

We have more than 5 Groups which have 500000+ Members and some Pages have more than 100000+ members. If you want to post your article on our website/FB Group/FB Page please contact on [email protected] or 8076671483

Buy This Ad Space @$50 per Month, Ad Size 600X200 Contact on: [email protected] or 8076671483

Path variable is set for providing path for all Java tools like java, javac, javap, javah, jar, appletviewer which are used in java programming. All these tools are available in bin folders so we set path upto bin folders.

Classpath variable is set for providing a path for predefined Java classes which is used in our application. All classes are available in lib/rt.jar so we set classpath upto lib/rt.jar.

Cloud computing is the on demand availability of computer system resources, especially data storage and computing power, without direct active management by the user.

College Projects Related to Java, AWT, C Projects for College, C++ Projects for College, Android Projects.

Download Projects

Adsense Advertisements


Buy This ads Space 8076671483

Buy This Ad Space @$120 per Month, Ad Size 300X600 Contact on: [email protected] or 8076671483 Try this Keyword C++ Programs