C 语言中的排序数组函数



我写了这个函数来对整数数组进行排序,这里的标志是按升序还是降序对数组进行排序的指标,大小是数组的大小。你能告诉我我在哪里写错了什么吗,我也检查了算法。

void sortArray(int a[], int flag, int size) {
    int temp, index;
    int start = 0;
    int smallest = start;
    if (flag) {
        while (start < size) {
            index = start;
            while (index < size) {
                if(a[index] < a[smallest]) {
                    smallest = index;
                }
                index++;
            }
            temp = a[smallest];
            a[smallest] = a[start];
            a[start] = temp;
            start++;
        }
    }
    else{
        while (start < size) {
            index = start;
            while (index < size) {
                if(a[index] > a[smallest]) {
                   smallest = index;
                }
                index++;
            }
            temp = a[smallest];
            a[smallest] = a[start];
            a[start] = temp;
            start++;
       }
   }
}

在第二个while循环之前添加smallest = index;,如下所示

    if (flag) {
    while (start < size) {
        index = start;
        smallest = index;
        while (index < size) {
            if(a[index] < a[smallest]) {
                smallest = index;
            }
            index++;
        }
        temp = a[smallest];
        a[smallest] = a[start];
        a[start] = temp;
        start++;
    }
}

如果没有这个添加,你的循环会继续检查已经排序的元素,这会弄乱算法

最新更新