gpt4 book ai didi

c - 为什么我的快速排序算法不适用于重复元素?

转载 作者:行者123 更新时间:2023-11-30 15:12:10 24 4
gpt4 key购买 nike

我用 C 实现了快速排序算法来对数组的元素进行排序。它适用于所有情况,除非数组具有两个或多个相等元素。我一直在尝试修复它并一直在调试它,但当存在重复元素时,我似乎无法让它工作。

如果您能帮助我更改代码以使其也适用于重复元素,我将不胜感激。

#include <stdio.h>
#include <stdlib.h>

//Random Array Length
#define L 10
#define MAX 100

void smarter_sort(int[],int,int);
void swap(int[],int,int);
int choose_piv(int[],int,int);

int main(){

int i, a[L];

//Generate an array of random numbers
for(i=0; i<L; i++)
a[i]= rand() % (MAX+1);

//Unsorted Array
printf("\nUnsorted array: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);

//Sorted Array
smarter_sort(a,0,L-1);
printf("\nSorted array: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);
return 0;
}

//Recursively defined quicksort (Pseudo-code listing 1.9)
void smarter_sort(int a[], int l, int r){
if(r > l){
int piv = choose_piv(a, l, r);
smarter_sort(a, l, piv-1);
smarter_sort(a, piv+1, r);
}
}

//Swap Elements
void swap(int a[], int i, int j){
int t=a[i];
a[i]=a[j];
a[j]=t;
}

//Choosing the pivot (pseudo-code listing 1.10)
int choose_piv(int a[], int l, int r){
//defining pointers and pivot
int pL = l, pR = r;
int piv = l;

while (pL < pR){
//finding the first left element greater than piv
while(a[pL] < a[piv])
pL++;

//finding the first right element greater than piv
while(a[pR] > a[piv])
pR--;

//swapping if the pointers do not overlap
if(pL < pR)
swap(a, pL, pR);

if(a[pL]==a[piv]||a[pR]==a[piv]){
pL++;
pR--;
}
}
//swapping and returning the rightmost pointer as the pivot
swap(a, piv, pR);
return pR;
}

最佳答案

这是您修改后的代码,以便即使数组包含相同元素也能正常工作:

 #include <stdio.h>
#include <stdlib.h>

//Random Array Length
#define L 10
#define MAX 100

void smarter_sort(int[],int,int);
void swap(int[],int,int);


int main(){

int i, a[L];

//Generate an array of random numbers
for(i=0; i<L; i++)
a[i]= rand() % (MAX+1);

//Unsorted Array
printf("\nUnsorted array: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);

//Sorted Array
smarter_sort(a,0,L-1);
printf("\nSorted array: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);
return 0;
}

//Recursively defined quicksort (Pseudo-code listing 1.9)
void smarter_sort(int arr[], int left, int right) {
int i = left, j = right;
int pivot = arr[(left + right) / 2];


while (i <= j) {
while (arr[i] <pivot)
i++;
while (arr[j]>pivot)
j--;
if (i <= j) {
swap(arr,i,j);
i++;
j--;
}
};


if (left < j)
smarter_sort(arr, left, j);
if (i < right)
smarter_sort(arr, i, right);
}


//Swap Elements
void swap(int a[], int i, int j){
int t=a[i];
a[i]=a[j];
a[j]=t;
}

关于c - 为什么我的快速排序算法不适用于重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206881/

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