【发布时间】:2025-11-28 23:20:05
【问题描述】:
我试图用 C 编写一个快速排序实现已经 2 天了,但它不起作用。我的意思是,它确实可以编译,但输出不是我所期望的。
我一直在研究一本 Data Struct 的书,它被翻译成葡萄牙语,我的母语,无论如何...我将通过下面的说明以及我的代码。
QuickSort Image Partition Image
//
// Quick sort V2.c
// IFTM Exercises
//
// Created by Lelre Ferreira on 7/9/19.
// Copyright © 2019 Lelre Ferreira. All rights reserved.
//
#define size 5
#include <stdio.h>
void printfArrays(int *array);
void receiveArray(int *array);
int QuickSortPartition(int *array, int begin, int end);
void QuickSortFunction(int *array, int begin, int end);
int main (int argc, const char * argv[]){
int array[size];
receiveArray(array);
printfArrays(array);
return 0;
}
void receiveArray(int* array){
int i = 0;
for (i = 0; i < size; i++) {
printf("Insert value of [%d]: ", i);
scanf("%d", &array[i]);
}
}
void printfArrays(int *array){
int i = 0;
for (i = 0; i < size; i++) {
printf("Value sorted: %d\n", array[i]);
}
}
int QuickSortPartition(int *array, int begin, int end){
int pivot = array[end];
int i = (begin - 1), j = 0;
for (j = begin; j <= end - 1; j++) {
if (array[j] <= pivot) {
i++;
array[i] = array[j];
}
}
array[i + 1] = array[end];
return (i + 1);
}
void QuickSortFunction(int *array, int begin, int end){
if (begin < end) {
int pivot = QuickSortPartition(array, begin, end);
QuickSortPartition(array, begin, pivot - 1);
QuickSortPartition(array, pivot + 1, end);
}
}
【问题讨论】:
-
您的
main从未调用任何排序函数。 -
使用调试器学习是个好主意。通过这种方式,您可以查看调用了哪些函数、中间状态是什么,并且更容易查明错误。
-
@Lelre Ferreira 很明显QuickSortPartition函数不正确。
-
OT: about:
int main (int argc, const char * argv[]){这将导致编译器输出两条关于未使用参数的警告消息。 (argc和argv)建议使用main()的其他有效签名——int main( void ) -
看来
QuickSortFunction是为了递归,这很常见,但它不是。它应该调用自己(两次),而是调用QuickSortPartition。
标签: c arrays sorting quicksort partitioning