gpt4 book ai didi

c - c 中的随机快速排序产生不正确/部分排序的输出

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:23 25 4
gpt4 key购买 nike

我正在尝试使用随机枢轴实现快速排序

void QuickSort(int *arr,int left,int right){

if(right-left+1 > 2){

int i = 0,storeIndex = left;
int pivot = left + (int)(rand() % (right-left+1));

swap(&arr[pivot],&arr[right]);

for(i = left; i < right; i++){

if(arr[i] < arr[right]){
swap(&arr[i],&arr[storeIndex]);
storeIndex++;
}
}

swap(&arr[storeIndex],&arr[right]);
QuickSort(arr,left,storeIndex-1);
QuickSort(arr,storeIndex+1,right);
}
}

但这给出了排序不正确的输出

未排序 [81,87,47,59,81,18,25,40,56,0]

排序 [0,18,25,40,56,47,59,81,87,81]

我的算法有问题,因为在 python 中类似的东西运行良好

最佳答案

条件显然是错误的:如果你传递一个 2 元素数组,它不会被排序,因为:

left = 0
right = 1
right - left + 1 = 2 not greater than 2

关于c - c 中的随机快速排序产生不正确/部分排序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com