C Programming Code Examples C > Sorting Searching Code Examples C Program to accept Sorted Array and do Search using Binary Search C Program to accept Sorted Array and do Search using Binary Search This C Program accepts the sorted array and does search using Binary search. Binary search is an algorithm for locating the position of an item in a sorted array. A search of sorted data, in which the middle position is examined first. Search continues with either the left or the right portion of the data, thus eliminating half of the remaining search space. In other words, a search which can be applied to an ordered linear list to progressively divide the possible scope of a search in half until the search object is found. #include <stdio.h> void main() { int array[10]; int i, w, x, temp, keynum; int low, mid, high; printf("Enter the value of x \n"); scanf("%d", &x); printf("Enter the elements one by one \n"); for (i = 0; i < x; i++) { scanf("%d", &array[i]); } printf("Input array elements \n"); for (i = 0; i < x; i++) { printf("%d\n", array[i]); } /* Bubble sorting begins */ for (i = 0; i < x; i++) { for (w = 0; w < (x - i - 1); w++) { if (array[w] > array[w + 1]) { temp = array[w]; array[w] = array[w + 1]; array[w + 1] = temp; } } } printf("Sorted array is...\n"); for (i = 0; i < x; i++) { printf("%d\n", array[i]); } printf("Enter the element to be searched \n"); scanf("%d", &keynum); /* Binary searching begins */ low = 1; high = x; do { mid = (low + high) / 2; if (keynum < array[mid]) high = mid - 1; else if (keynum > array[mid]) low = mid + 1; } while (keynum != array[mid] && low <= high); if (keynum == array[mid]) { printf("SEARCH SUCCESSFUL \n"); } else { printf("SEARCH FAILED \n"); } }