我正在用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 half\n\n"); //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("%d\n",array[i]);
    }

    printf("\nbreak\n\n");

    quicksort(0,ARRSZ-1);

    for(int i = 0; i < ARRSZ; i++){
        printf("%d\n",array[i]);
    }

    return 0;
}

它始终到达“ printf(” \ nbreak \ n \ n“);” (第46行) 有时“ printf(” \ nqs前半\ n \ n“);” (第23行)。

然后Windows提示它停止工作,并且输出显示:

进程返回:-1073741795(0xC000001D)

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

谢谢您的回答。

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

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

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 last) {

   int pivotIndex;
   if (first < last) {

      partition(theArray,last,pivotIndex);

      // sort regions S1 and S2
      quicksort(theArray,pivotIndex-1);
      quicksort(theArray,pivotIndex+1,last);
   }
}

如果您仍然对某些问题感到困惑,可以随时在评论中提问

本文链接:https://www.f2er.com/3025589.html

大家都在问