这是quicksort算法在c中的实现,对于给定的输入,我的程序将输出为4 5 -343534 1
,我是编程新手,请指出我的错误
#include<stdio.h>
#include<stdlib.h>
int partition(int* A, int start, int end) {
int pivot = A[end];
int pindex = start;
for (int i = 0; i < end; i++) {
if (A[i] <= pivot) {
int temp = A[i];
A[i] = A[pindex];
A[pindex] = temp;
pindex = pindex + 1;
}
}
int temp = A[end];
A[end] = A[pindex];
A[pindex] = temp;
return pindex;
}
void quicksort(int* A, int start, int end) {
if (start < end) {
int pindex = partition(A, start, end);
quicksort(A, start, pindex - 1);
quicksort(A, pindex+1, end);
}
}
int main() {
int* a = (int*)malloc(sizeof(int) * 4);
a[0] = 1;
a[1] = 5;
a[2] = 4;
a[3] = 2;
quicksort(a, 0, 3);
printf("%d %d %d %d", a[0], a[1], a[2], a[3]);
system("pause");
}
最佳答案
您的问题来自partition
函数:i
变量应该从astart
开始,而不是从0开始:
int partition(int* A, int start, int end)
{
int pivot = A[end];
int pindex = start;
for (int i = start; i < end; i++) {
if (A[i] <= pivot) {
int temp = A[i];
A[i] = A[pindex];
A[pindex] = temp;
pindex = pindex + 1;
}
}
int temp = A[end];
A[end] = A[pindex];
A[pindex] = temp;
return pindex;
}
您的代码可以通过以下方式得到改进:定义
swap
函数以避免重复:#include<stdio.h>
#include<stdlib.h>
void print_array(int *A, int size)
{
for (int i = 0; i < size; ++i)
printf("%d ", A[i]);
puts("");
}
void swap(int *A, int i, int j)
{
if (i == j)
return ;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
int partition(int* A, int start, int end) {
int pivot = A[end];
int pindex = start;
for (int i = start; i < end; i++) {
if (A[i] <= pivot) {
swap(A, i, pindex);
pindex = pindex + 1;
}
}
swap(A, end, pindex);
return pindex;
}
void quicksort(int* A, int start, int end) {
if (start < end) {
int pindex = partition(A, start, end);
quicksort(A, start, pindex - 1);
quicksort(A, pindex+1, end);
}
}
int main() {
int i, size = 32;
int* a = malloc(sizeof * a * size);
for (i = 0; i < size; ++i)
a[i] = rand()%100;
print_array(a, size);
quicksort(a, 0, size-1);
print_array(a, size);
return 0;
}
给予:
83 86 77 15 93 35 86 92 49 21 62 27 90 59 63 26 40 26 72 36 11 68 67 29 82 30 62 23 67 35 29 2
2 11 15 21 23 26 26 27 29 29 30 35 35 36 40 49 59 62 62 63 67 67 68 72 77 82 83 86 86 90 92 93
关于c - 快速排序算法在C中的实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53536033/