/* Demonstration of how one could use a binary search algorithm to look up a student's name given his ID number. A group of records is read in, and then sorted. Then, the user supplies the key for the search (a sample ID #), and the list is searched with a binary algorithm. */ #include #include #define MAXSTUDENTS 50 /* Declaration statement */ void id_swap(long int *k, long int *l) { long int temp; temp = *k; *k = *l; *l = temp; } void grade_swap(int *grade1, int *grade2) { int temp; temp = *grade1; *grade1 = *grade2; *grade2 = temp; } void bsort2( long int id[], int grade[],int n) { int last, k, i, kk; printf("Sorting\n"); last = n - 1; do { k = 0; for (i = 1; i <= last; i++) { if (id[i - 1] > id[i]) { id_swap(&id[i - 1], &id[i]); grade_swap(&grade[i - 1], &grade[i]); k = i; } } last = k; } while (k != 0); } int binary(long int id[], long int key,int n) { int a, b, middle; a = 0; b = n; do{ middle = (a+b)/2; if( id[middle] < key ) a = middle+1; else if( id[middle] > key) b = middle-1; else return(middle); }while( a<=b ); /* If program reaches this point, no match was found, and the value returned will indicate this. */ return(-1); } main() { /* Declaration Statements */ long int id[MAXSTUDENTS], key; int i, n, flag, cont, yes_no, grade[MAXSTUDENTS]; do { printf("How many students? ( <%4d)",MAXSTUDENTS); scanf("%d",&n); }while( n>MAXSTUDENTS ); printf("Enter students' names and ID #'s\n"); printf("in this format ->ID:9421234[ENTER] (no spaces)\n"); printf(" ->Grade:49[ENTER]\n"); for( i=0; i