Binary Search Program using c
Well guys, I am back with a basic concept which one should know to continue with coding. Its a simple binary search implementation using C programming language. Using this concept we can implement it in every program in which any searching operation is required. But be sure that this code works for a sorted array. If you don't know sorting then you can check out the sorting concept which you can find in our website. Now have a look at the code....
Program Code:
Program Code:
#include<stdio.h> int main() { int c, high, low, middle, n, search, array[100]; printf("Enter number of elements:"); scanf("%d",&n); printf("Enter %d integers:", n); for (c = 0; c < n; c++) scanf("%d",&array[c]); printf("Enter value to find:"); scanf("%d", &search); low = 0; high = n - 1; middle = (low+high)/2; while (low <= high) { if (array[middle] < search) low = middle + 1; else if (array[middle] == search) { printf("\n%d found at location %d.\n", search, middle+1); break; } else high = middle - 1; middle = (low + high)/2; } if (low > high) printf("Not found! %d is not present in the list.\n", search); getch(); return 0; }
As you can see from the above code, its easy as a piece of cake! The concept here is to take the middle element of the array which have initialized during entering the values. The middle value can be obtained by dividing the sum of lower and higher index of the array.
When we get the middle value, we can use it as reference element to compare with the key value. As the input is a sorted array, so if the middle value is equal to key then its the end of searching. If its not so, then we check if the key element is greater or smaller in size. If greater than key, then split the array, increment the middle value by one unit and assign it to lower index. If smaller than key, then decrease middle value by one unit, and assign it to the higher index of the array.
Well, if its the case that you want to enter the values in unsorted manner, then a little modification in the code required, you just have to add the sorting logic. Now have a look at the output.
Sample Output:
That's it guys... Thanks for stopping by.. If you have any query or anything to say then you can use the comment section or contact me direct through my profile. And share and subscribe.. Both are free... ;)
Comments
Post a Comment