c - 这个快速排序程序有什么问题?

标签 c quicksort

我写了下面的快速排序程序。但是,它似乎没有用。有人能指出这个程序有什么问题吗?

#include<stdio.h>

void swap (int a[], int left, int right) {
    int temp;
    temp=a[left];
    a[left]=a[right];
    a[right]=temp;
} 

void printarray(int a[], int);
void partition( int a[], int low, int high );

void quicksort( int a[], int low, int high ) {
    srand((unsigned int)time(0));
    partition( a, low, high );
} 

void partition( int a[], int low, int high ) {
    int left, right;
    int pivot_item, pivot;

    left = low;
    right = high;

    if ((right - left) <= 1)
        return;

    pivot = rand() % (high - low + 1);
    pivot_item = a[pivot];

    while (left < right) {
        while (a[left] <= pivot_item)
            left++;

        while (a[right] > pivot_item)
            right--;

        swap(a,left,right);
    }

    partition(a, low, right-1);
    partition(a, right+1, high);

    return;
}

int main() {
    int a[] = {24, 5, 3, 35, 14, 23, 19, 43, 2, 1};
    int i, n = 10;

    printf("\nUnsorted elements: \n");
    printarray(a,n);
    quicksort(a,0,n-1);
    printf("\nSorted elements: \n");
    printarray(a,n);

}


void printarray(int a[], int n) {
    int i;

    for (i = 0; i < n; i++)
        printf(" %d ", a[i]);
    printf("\n");
}

每次我得到如下不同的输出。

:>~/prgms$ ./a.out 

Unsorted elements: 
 24  5  3  35  14  23  19  43  2  1 

Sorted elements: 
 14  2  19  1  5  23  43  35  3  24 

:>~/prgms$ ./a.out 

Unsorted elements: 
 24  5  3  35  14  23  19  43  2  1 

Sorted elements: 
 1  5  35  14  23  19  3  24  43  2 

最佳答案

除了stark指出的错误,可以通过更改来修复

pivot = rand() % (high - low + 1);

pivot = low + rand() % (high - low + 1);

还有两个错误。 首先,

    while( a[left] <= pivot_item )
    left++;

应该是

    while (a[left] < pivot_item) left++;

否则,索引 left 可以递增到超出主元位置甚至数组末尾,从而导致未定义的结果。 二、

if ((right - left) <= 1)
return;

应该是

if (right - left < 1) return;

否则,长度为2的分区不排序。

关于c - 这个快速排序程序有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19458438/

相关文章:

c - fork 从哪里开始执行表单?

c - 以秒为单位的朱利安时间戳的差异

c - 在c中读取文件错误,不知道错误是什么。 - 内存分配错误?

C转MIPS的麻烦

c - 以 HDF5 格式表示可变长度二维数组?

algorithm - 如何通过反转子序列对排列进行排序(取自 Skiena 第 3 版)

algorithm - 快速排序三向分区

python - 如何改进 python 中的快速排序枢轴选择?

java - 为什么归并排序和快速排序操作的顺序会导致第二个操作运行得更快?

java - 使用quickSort对数组进行排序(JAVA)