C examples for Data Structure:Search
Find a Data Element Using a Binary Search
#include <stdio.h> int myArray[50];/* w w w . j a v a 2 s . c om*/ int count = 0; int searchData(int intData) { int intLowBound = 0; int intUpBound = count -1; int intMidPoint = -1; int intCompare = 0; int intNum = -1; while(intLowBound <= intUpBound) { intCompare++; intMidPoint = intLowBound + (intUpBound - intLowBound) / 2; if(myArray[intMidPoint] == intData) { intNum = intMidPoint; break; } else { if(myArray[intMidPoint] < intData) { intLowBound = intMidPoint + 1; } else { intUpBound = intMidPoint -1; } } } printf("Total comparisons made: %d" , intCompare); return intNum; } int main() { int intPosition, intData, i; count = 10; printf("Enter the 10 integers in increasing order, \nseparated by white spaces: "); for (i=0; i < count; i++) scanf("%d", &myArray[i]); fflush(stdin); printf("Enter the number to search: "); scanf("%d", &intData); intPosition = searchData(intData); if(intPosition != -1) { printf("\nData Element Found at Position "); printf("or Location: %d" ,(intPosition+1)); } else printf("\nData Element not found."); }