/** * Program to test sorting and searching functions: * * Generate array of N random values. * * Sort the array. * * Check that the result is sorted. * * Print results, and prompt for search input. * * Input: Number of elements, and search input. * * Output: Whether sort worked, and results of search. */ #include #include /* ---- Function declarations ---- */ /* Note use of C99 variable-length arrays as parameters (where * appropriate) */ void test_and_print(int n); void generate_data(int n, int nums[n]); void print_data(int n, int nums[n]); int find_index_of_max(int nums[], int last); void selection_sort(int n, int nums[n]); void is_sorted(int n, int nums[n]); int binary_search(int elem, int n, int nums[n]); /* ---- Main program ---- */ int main(void) { int n; printf("how many numbers?\n"); if ((scanf("%d", &n) != 1) || (n <= 0)) { printf("input not a positive number\n"); return EXIT_FAILURE; } test_and_print(n); return EXIT_SUCCESS; } /* ---- Function definitions ---- */ /* * Generate data (n elements), sort, check, and print results, as described */ void test_and_print(int n) { int nums[n]; int elem; int search_result; generate_data(n, nums); selection_sort(n, nums); is_sorted(n, nums); printf("\nnumbers after sort:\n"); print_data(n, nums); printf("\nenter a number to search for\n"); if (scanf("%d", &elem) == 1) { search_result = binary_search(elem, n, nums); if (search_result == -1) { printf("not found\n"); } else { printf("found at %d\n", search_result); } } else { printf("not a number\n"); } } /* * Generate n elements and put in nums */ void generate_data(int n, int nums[n]) { int i; for (i = 0; i < n; ++i) { nums[i] = rand(); } } /* * Print contents of nums array. */ void print_data(int n, int nums[n]) { int i; for (i = 0; i < n; ++i) { printf("%d\n", nums[i]); } } /* * Find largest element in nums[0 .. last] and return its index. */ int find_index_of_max(int nums[], int last) { int max; /* index of maximum so far */ int i; max = 0; for (i = 1; i <=last; ++i) { if (nums[i] > nums[max]) max = i; } return max; } /* * Sort nums (array of size n). */ void selection_sort(int n, int nums[n]) { int last; int index_of_max; int temp; for (last = n-1; last > 0; --last) { index_of_max = find_index_of_max(nums, last); /* exchange nums[index_of_max] and nums[last] */ temp = nums[index_of_max]; nums[index_of_max] = nums[last]; nums[last] = temp; } } /* * Check that nums (array of size n) is sorted. * Prints messages about anything not sorted. */ void is_sorted(int n, int nums[n]) { int i = 0; for (i = 0; i < n-1; ++i) { if (nums[i] > nums[i+1]) printf("out of order at %d!\n",i); } } /* * Binary search -- returns index of elem in nums, or -1 if not found. */ int binary_search(int elem, int n, int nums[n]) { int start = 0; int last = n-1; int mid; while (start <= last ) { mid = (start + last) / 2; if (elem < nums[mid]) { last = mid - 1; } else if (elem > nums[mid]) { start = mid + 1; } else { return mid; } } return -1; }