为什么我这个快排没有用?

Sheldon
  • 24
#include<stdio.h>
void swap(int *a, int *b) {
    int temp;
    temp = *b;
    *b = *a;
    *a = temp;
}


int Rand(int low, int high) {
    int size = high - low + 1;
    return low + rand() % size;
}
int    Partition(int a[],int start,int end,int length) {
    int index = Rand(start, end);
    swap(a[index], a[end]);

    int small = start - 1;
    for (index = start; index < end; ++index) {
        if (a[index] < a[end]) {
            ++small;
            if (small != index)
                swap(a[index], a[small]);
        }
    }

    ++small;
    swap(a[small], a[end]);
    printf("\n排序过程 ");
    for (int j = 0; j < 9; j++) {
        printf("%d ", a[j]);
    }

    return small;
}

void Qsort(int a[], int length, int start, int end) {
    if (start = end)
        return;

    int index = Partition(a, start, end, length);
    if (index > start) {
        Qsort(a, start, index - 1, length);
        printf("\n随机选择 a[%d](%d)", index, a[index]);
    }
    if (index < end) {
        Qsort(a, index + 1, end, length);
        printf("\n随机选择 a[%d](%d)", index, a[index]);
    }
}


void main() {
    int a[] = { 7,6,44,8,2,3,1,9,6 };

    Qsort(a, 9, 0, 8);

    for (int j = 0; j < 9; j++) {
        printf("%d ", a[j]);
    }
}

运行结果如下:
图片描述

各位帮帮忙

回复
阅读 2.4k
3 个回答

swap写的有问题,并没有修改当前数组.你把当前数组也传递进去,然后修改对应索引位置的元素.

这个程序能够编译通过就奇怪了

快排的参数传入错误了,没注意

宣传栏