a.txt: 读入数据
b.txt: 写入排序数据
c.txt: 写入查找结果
#include const int maxn = 1000;int num[maxn], n;void swap(int* x,int* y) { *x ^= *y; *y = *x^*y; *x = *x^*y;}void finput() { printf("--------\nread data from a.txt\n--------\n\n"); FILE* fin = fopen("a.txt","r"); n = 0; while ( fscanf(fin,"%d",&num[n]) != EOF ) { n++; } fclose(fin);}void bubble() { printf("--------\nstart bubbling sort algorithm\n"); for (int i = n-1; i > 0; --i) { for (int j = 0; j < i; ++j) { if (num[j] > num[j+1]) { swap(&num[j],&num[j+1]); } } } printf("write the result of sort in b.txt\n--------\n\n"); FILE* fout = fopen("b.txt","w"); for (int i = 0; i < n; ++i) { fprintf(fout,"%d\n", num[i]); } fclose(fout);}int rbesearch(int low,int high,int v) { // recursive binary search // return the index of v. if not exists, return -1. if (low == high) { if (num[low] == v) return low; return -1; } if (num[low] == v) return low; int mid = (low+high)/2; if (num[mid] < v) { return rbesearch(mid+1,high,v); } else { return rbesearch(low,mid,v); }}int nrbesearch(int low,int high,int v) { // non-recursive binary search // return the index of v. if not exists, return -1. while (low < high) { int mid = (low+high)/2; if (num[mid] < v) { low = mid+1; } else { high = mid; } } if (low == high && num[low] == v) { return low; } return -1;}void search() { printf("--------\n"); printf("Start search.\n"); printf("The results will be written in c.txt\n"); printf("please input a num. if num = -123456, quit.\n"); FILE* file=fopen("c.txt","w"); while (true) { int v; scanf("%d", &v); if (v == -123456) break; int rb = rbesearch(0,n-1,v); int nrb = nrbesearch(0,n-1,v); fprintf(file,"input: %d\n",v); fprintf(file,"the result of recursive binary search: %d\n", rb); fprintf(file,"the result of non-recursive binary search: %d\n\n", nrb); printf("the result of recursive binary search: %d\n", rb); printf("the result of non-recursive binary search: %d\n\n",nrb); } fclose(file); }int main() { finput(); bubble(); search(); return 0;}