/* File: search.c Search for a number in a sorted list. */ #include #include "genlib.h" #include "simpio.h" #define SENTINEL -1 #define MAX_ITEMS 100 int ReadArray(int A[], int max_size) ; void SelectionSort(int A[], int size) ; int FindSmallest(int A[], int start, int stop) ; main() { int A[MAX_ITEMS], items, i, number ; printf("Enter items, one per line.\n") ; printf("End with sentinel: %d\n", SENTINEL) ; items = ReadArray(A, MAX_ITEMS) ; if (items == -1) { printf("Too many items!!!\n") ; } else { SelectionSort(A, items) ; printf("\nSorted list:\n") ; for(i = 0 ; i < items ; i++) { printf("A[%d] = %d\n", i, A[i]) ; } } printf("\nEnter number to find:\n" ) ; number = GetInteger() ; i = Find(A, items, number) ; printf("%d is number %d on the list\n", A[i], i+1) ; } /* Use Binary Search to find a number */ int Find(int A[], int size, int number) { int left, right, middle ; left = 0 ; right = size - 1 ; while (left <= right) { middle = (left + right) / 2 ; if (number == A[middle]) return(middle) ; if (number < A[middle]) { right = middle - 1 ; } else { left = middle + 1 ; } } } /* Use Selection Sort to sort the array */ void SelectionSort(int A[], int size) { int unsorted, smallest_index, temp ; for(unsorted=0; unsorted < size-1; unsorted++){ smallest_index = FindSmallest(A,unsorted,size-1); /* swap values */ temp = A[smallest_index] ; A[smallest_index] = A[unsorted] ; A[unsorted] = temp ; } } /* Find smallest value in array A from start to stop. */ int FindSmallest(int A[], int start, int stop) { int smallest_value, smallest_index, i ; smallest_index = start ; smallest_value = A[start] ; for (i = start+1 ; i <= stop ; i++){ if (A[i] < smallest_value) { smallest_index = i ; smallest_value = A[i] ; } } return(smallest_index) ; } /* Read integers into array. Make sure that array size is not exceeded. If so, return -1, otherwise return # of items. */ int ReadArray(int A[], int max_size) { int i, value ; i = 0 ; while (TRUE) { value = GetInteger() ; if (value == SENTINEL) break ; if (i == max_size) return(-1) ; A[i] = value ; i++ ; } return(i) ; }