C Program to implement Binary search. Binary search technique is simple searching technique which can be applied if the items to be compared are either in ascending order or descending order. The general idea used in binary search is similar to the way we search for the telephone number of a person in the telephone directory. Binary search is the divide and conquer strategy.Read more about C Programming Language.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*********************************************************** | |
* You can use all the programs on www.c-program-example.com | |
* for personal and learning purposes. For permissions to use the | |
* programs for commercial purposes, | |
* contact [email protected] | |
* To find more C programs, do visit www.c-program-example.com | |
* and browse! | |
* This program was originally published at | |
* http://www.c-program-example.com/2011/09/c-program-for-binary-search.html | |
* Happy Coding | |
***********************************************************/ | |
/*C Program for Binary search */ | |
#include<stdio.h> | |
int main() { | |
int n, a[30], item, i, j, mid, top, bottom; | |
printf("Enter how many elements you want:\n"); | |
scanf("%d", &n); | |
printf("Enter the %d elements in ascending order\n", n); | |
for (i = 0; i < n; i++) { | |
scanf("%d", &a[i]); | |
} | |
printf("\nEnter the item to search\n"); | |
scanf("%d", &item); | |
bottom = 1; | |
top = n; | |
do { | |
mid = (bottom + top) / 2; | |
if (item < a[mid]) | |
top = mid - 1; | |
else if (item > a[mid]) | |
bottom = mid + 1; | |
} while (item != a[mid] && bottom <= top); | |
if (item == a[mid]) { | |
printf("Binary search successfull!!\n"); | |
printf("\n %d found in position: %d\n", item, mid + 1); | |
} else { | |
printf("\n Search failed\n %d not found\n", item); | |
} | |
return 0; | |
} |
Read more Similar C Programs C Basic Search Algorithms.
You can easily select the code by double clicking on the code area above.
To get regular updates on new C programs, you can Follow @c_program
You can discuss these programs on our Facebook Page. Start a discussion right now,
our page!
Share this program with your Facebook friends now! by liking it
(you can send this program to your friend using this button)
Like to get updates right inside your feed reader? Grab our feed!
(c) www.c-program-example.com
One comment on “Binary search in C”