#include<stdio.h> #include<stdlib.h> #define MAX_SIZE 101 #define SWAP(x, y, t)((t) = (x), (x) = (y), (y) = t) #define COMPARE(x, y)((x) < (y)) ? -1 : ((x) == (y)) ? 0 : 1; void sort(int [], int); int binsearch(int list[], int searchnum, int left, int right) { int middle; int key; if(left <= right) { middle = (left + right) /2; key = COMPARE(list[middle], searchnum); if(key == -1) { return binsearch(list, searchnum, middle + 1, right); } else if(key == 0) { return middle; } else if(key == 1) { return binsearch(list, searchnum, left, middle -1); } } return -1; } void perm(char *list, int i, int n) { int j, temp; if(i == n) { for(j = 0; j <= n; j++) { printf("%c", list[j]); } printf(" "); } else { for(j = i; j <= n; j++) { SWAP(list[i], list[j], temp); perm(list, i + 1, n); SWAP(list[i], list[j], temp); } } printf(" "); } int main() { int i, n = 10; int list[MAX_SIZE]; for(i = 0; i < n; i++) { list[i] = rand() % 1000; printf("%d ", list[i]); } printf("******************* "); sort(list, n); for(i = 0; i < n; i++) { printf("%d ", list[i]); } int result = binsearch(list, list[2], 0, n); printf("result = %d ", result); printf("******************* "); char a[] = {'a', 'b', 'c'}; perm(a, 0, 2); return 1; } void sort(int list[], int n){ int i, j, min, temp; for(i = 0; i < n -1; i++) { min = i; for(j = i + 1; j < n; j++) { if(list[j] < list[min]) { min = j; } } SWAP(list[i], list[min], temp); } }