我正在用 C 进行快速排序,但看不到有什么问题



我正在尝试在 C 中进行快速排序以进行练习,它正在崩溃,我看不出为什么。

到目前为止,我拥有的代码(它只是一侧抛出的数字高于枢轴而另一侧比枢轴小的部分 + 它只是对"数组"进行排序(:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRSZ 10 //ARRay SiZe
int array[ARRSZ];
void quicksort(int start, int end){
int pivot = start + (end - start)/2;
for(int i = start; i < pivot; i++){
if(array[i] > pivot){
int x = array[i];
for(int j = i; i < pivot; j++){
array[j] = array[j+1];
}
array[pivot] = x;
pivot--;
}
}
printf("nqs first halfnn"); //I put these here afterwards so I could see how far the program got.
for(int i = end; i > pivot; i--){
if(array[i] < pivot){
int x = array[i];
for(int j = i; i > pivot; j--){
array[j] = array[j-1];
}
array[pivot] = x;
pivot++;
}
}
}
int main()
{
srand(time(NULL));
for(int i = 0; i < ARRSZ; i++){
array[i] = rand() % (ARRSZ*2) + 1 - ARRSZ; //Wanted to have numbers form -ARRSZ to +ARRSZ
printf("%dn", array[i]);
}
printf("nbreaknn");
quicksort(0, ARRSZ-1);
for(int i = 0; i < ARRSZ; i++){
printf("%dn", array[i]);
}
return 0;
}

它一直到达"printf("break\"(;"(第 46 行( 有时是"printf("qs 前半部分\"(;">(第 23 行(。

然后窗口说它停止工作,输出说:

返回的进程: -1073741795 (0xC000001D(

我正在使用CodeBlocks 17.12,Windows 7 Pro,如果它有帮助的话。

感谢您的任何回答。

对于分区功能,您可以使用以下算法有提示:

template <class DataType>
void partition(DataType theArray[], int first, int last,
int &pivotIndex) {
int pIndex = choosePivot(theArray, first, last);
// put pivot at position first
swap(theArray[pIndex], theArray[first]);
DataType pivot = theArray[first]; // copy pivot
int lastS1 = first;           // index of last item in S1
int firstUnknown = first + 1; //index of 1st item in unknown
// move one item at a time until unknown region is empty
for (; firstUnknown <= last; ++firstUnknown) {
if (theArray[firstUnknown] < pivot)          
++lastS1;
swap(theArray[firstUnknown], theArray[lastS1]);
}
// place pivot in proper position and mark its location
swap(theArray[first], theArray[lastS1]);
pivotIndex = lastS1;
}

您可以使用以下算法的快速排序功能有编写代码的提示:

void quicksort(DataType theArray[], int first, int last) {
int pivotIndex;
if (first < last) {
partition(theArray, first, last, pivotIndex);
// sort regions S1 and S2
quicksort(theArray, first, pivotIndex-1);
quicksort(theArray, pivotIndex+1, last);
}
}

如果您仍然对某些事情感到困惑,可以在评论中自由提问

最新更新