快速排序的一个小坑

第一版不知为何一直报错,代码如下


int partition(int a[], int low, int high)
{
    int key = a[low];
    while (low < high)
    {
        while (a[high] >= key && low<high) high--;
        a[low] = a[high];
        while (a[low] <= key && low<high) low++;
        a[high] = a[low];
    }
    printf("%d %d", low, high);
    printf("\n");
    a[low] = key;
    return low;

}

void quickSort(int a[], int low, int high)
{
    if (low == high) return;
    int pivot = partition(a, low, high);
    quickSort(a, low, pivot - 1);
    quickSort(a, pivot + 1, high);
}
int main()
{
    //int a[] = { 46,87,123,12,9,55,3 };
    //int a[] = { 1,2,3,4,5,6,7 };
    int a[] = { 7,6,5,4,3,2,1 };
    //insertSort(a, 7);
    // bbleSort(a, 7);
    // lectSort(a, 7);
    //mergeSort(a, 0, 6);
    quickSort(a, 0, 6);

    for (int i = 0; i < 7; i++)
        printf("%d ", a[i]);
    while (1);
    return 0;
}

后来发现,当low==pivot时,下面这句话会有问题:

    quickSort(a, low, pivot - 1);

于是改为:

    if (pivot > low)
        quickSort(a, low, pivot - 1);
    quickSort(a, pivot + 1, high);

仍然不对,最后发现是下面那句也要改:

    if (pivot > low)
        quickSort(a, low, pivot - 1);
    if(pivot<high)
        quickSort(a, pivot + 1, high);

但是书上和网上的标答都没有这么麻烦啊??最后发现:我的递归出口是low=hight,而标答是low>=high,如果这样一改,刚才的两句if也就不需要了:

void quickSort(int a[], int low, int high)
{
    if (low >= high) return;
    int pivot = partition(a, low, high);
    //if (pivot > low)
        quickSort(a, low, pivot - 1);
    //if(pivot<high)
        quickSort(a, pivot + 1, high);
}

猜你喜欢

转载自www.cnblogs.com/YuQiao0303/p/9609716.html