C语言 二分法查找 排序问题

在一个txt文件随机输入一序列数字,先用冒泡或选择排序进行排序,然后用二分查找进行查找(递归算法与非递归算法!)。
要求:
1、将排序的结果写入另一个文件。
2、将查找的数字和查找的结果(在数组中的位置)写入第三个个文件。

a.txt: 读入数据

b.txt: 写入排序数据

c.txt: 写入查找结果

#include <stdio.h>

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;
}

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答