C ++ Quicksort继续崩溃

时间:2015-10-10 01:51:34

标签: c++ algorithm runtime-error quicksort

我已经实现了快速排序以进行一些时间分析并且它会编译但在运行后继续崩溃,我无法弄清楚原因。另外我认为辅助函数的一个返回语句if(high == low)中有一个错误,我不知道这是否导致了我的问题?代码如下,它接收一个由40个随机生成的整数组成的数组。

int partition(int A[], int low, int high) {
   //Partition the array into two parts
   //Pre Condition: A[] must have more than 2 elements
   int mid = (low + high) / 2;
   int pivot = A[mid]; //Store the value at A[mid] in our pivot
   A[mid] = A[low]; //Make a "gap" at low
   while(low < high) {
      //The "gap" is currently at low
      while(low < high && A[high] >= pivot) {
         high--;
      }
      A[low] = A[high]; //"Gap" is now at A[high]
      while(low < high && A[low] <= pivot) {
         low++;
      }
      A[high] = A[low];
      A[low] = pivot;
   }
   return low;
}

void quickSort(int A[], int low, int high) {
   //QuickSort Helper Function
   //Pre Condition: A > 0
   //Post Condition: Partition of the array
   if(low == high) //***ERROR HERE***
      return;
   if(low + 1 == high) {
      if(A[low] > A[high]) {
         swap(A, high, low);
      }
      return;
   }
   //Assign the return value to pivotPos after running partition method
   int pivotPos = partition(A, low, high); 
   quickSort(A, low, pivotPos - 1); //Recursive call
   quickSort(A, pivotPos + 1, high); //Recursive call
   return;
}

void quickSort(int A[], int n) {
   //Quicksort sorting algorithm
   //Precondition: A < 0
   //Postcondition: Sorted array in ascending order
   quickSort(A, 0, n - 1); //call our helper function
}

0 个答案:

没有答案