快速排序不适用于10k元素

时间:2013-03-01 19:45:38

标签: c++ quicksort

我的老师给了我一个快速排序功能来使用和测试执行时间,但当它到达10,000个元素列表时,它会抛出堆栈溢出,我无法弄清楚原因。我在几台不同的计算机上测试了它,结果相同,在解析的10,000个元素中大约有9375个。

快速排序文件

#include "swap.h"

/** Chooses a pivot for quicksort's partition algorithm and swaps
 *  it with the first item in an array.
 * @pre theArray[first..last] is an array; first <= last.
 * @post theArray[first] is the pivot.
 * @param theArray  The given array.
 * @param first  The first element to consider in theArray.
 * @param last  The last element to consider in theArray. */
void choosePivot(int theArray[], int first, int last){
    //cerr << "choosePivot(array, " << first << ", " << last << ")\n";
    int mid = (last - first) / 2;
    if( (theArray[first] <= theArray[mid] &&
         theArray[mid] <= theArray[last]) ||
        (theArray[last] <= theArray[mid] &&
         theArray[mid] <= theArray[first]) ){
        // value at mid index is middle of values at first and last indices 
        swap(theArray[first], theArray[mid]);
    }else if( (theArray[first] <= theArray[last] &&
               theArray[last] <= theArray[mid]) ||
              (theArray[mid] <= theArray[last] &&
               theArray[last] <= theArray[first])){
        // value at last index is middle of values
        swap(theArray[first], theArray[last]);
    }
}


/** Partitions an array for quicksort.
 * @pre theArray[first..last] is an array; first <= last.
 * @post Partitions theArray[first..last] such that:
 *    S1 = theArray[first..pivotIndex-1] <  pivot
 *         theArray[pivotIndex]          == pivot
 *    S2 = theArray[pivotIndex+1..last]  >= pivot
 * @param theArray  The given array.
 * @param first  The first element to consider in theArray.
 * @param last  The last element to consider in theArray.
 * @param pivotIndex  The index of the pivot after partitioning. */
void partition(int theArray[],
               int first, int last, int& pivotIndex){
   // place pivot in theArray[first]
   choosePivot(theArray, first, last);
   int pivot = theArray[first];     // copy pivot

   // initially, everything but pivot is in unknown
   int lastS1 = first;           // index of last item in S1
   int firstUnknown = first + 1; // index of first item in
                                 // unknown

   // move one item at a time until unknown region is empty
   for (; firstUnknown <= last; ++firstUnknown)
   {  // Invariant: theArray[first+1..lastS1] < pivot
      //         theArray[lastS1+1..firstUnknown-1] >= pivot

      // move item from unknown to proper region
      if (theArray[firstUnknown] < pivot)
      {  // item from unknown belongs in S1
         ++lastS1;
         swap(theArray[firstUnknown], theArray[lastS1]);
      }  // end if

      // else item from unknown belongs in S2
   }  // end for

   // place pivot in proper position and mark its location
   swap(theArray[first], theArray[lastS1]);
   pivotIndex = lastS1;
}  // end partition

/** sorts the items in an array into ascending order.
 * @pre theArray[first..last] is an array.
 * @post theArray[first..last] is sorted.
 * @param theArray  The given array.
 * @param first  The first element to consider in theArray.
 * @param last  The last element to consider in theArray. */
void quicksort(int theArray[], int first, int last){
    int pivotIndex;

   if (first < last)
   {  // create the partition: S1, pivot, S2
      partition(theArray, first, last, pivotIndex);

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

swap.h文件

#ifndef _SWAP_H
#define _SWAP_H

/** Swaps two items.
 * @pre x and y are the items to be swapped.
 * @post Contents of actual locations that x and y represent are
 *       swapped.
 * @param x  Given data item.
 * @param y  Given data item. */
void swap(int& x, int& y){
   int temp = x;
   x = y;
   y = temp;
}  // end swap

#endif /* _SWAP_H */

和实施文件

//main.cpp
//Angelo Todaro
//Main driverto clock the timing efficiency of different sort algorithms for different sized lists

#include "quickSort.cpp"
#include <iostream>
#include <time.h>
using namespace std;

double diffclock(clock_t,clock_t);

int main(){
    clock_t begin, end;//clocks to store number of ticks at beginning and end
    srand(time(NULL));//initialize seed
    cout << "# of Elements\tQuick\n";
    for(int n = 10; n < 100000; n*=10){
        int* array = new int[n];
        cout << n << "\t\t";
        for(int i =0; i < n; i++){
            array[i]=rand()%1000;
        }


        //quick sort
        begin=clock();
        quicksort(array,0,n);
        end=clock();
        cout << diffclock(end,begin) << "\t";

    }

    return 0;
}


double diffclock(clock_t clock1, clock_t clock2){
    double diffticks = clock1-clock2;//finds difference between ticks
    double diffmili=diffticks/CLOCKS_PER_SEC;//turns tickes into miliseconds
    return diffmili;
}

2 个答案:

答案 0 :(得分:3)

这是一个递归的快速排序实现,也没有选择一个非常好的支点。给定一些输入,它可以为每个元素进行函数调用。堆栈上的10k调用很难处理。此时,只有具有随机数据的迭代就地快速排序才是一个很好的算法。

答案 1 :(得分:2)

当我debugged your code给你时,我可以看到,当你致电choosePivot时,只有一个元素,它正在完全删除

enter quicksort(array, 2, 3)
1  //content of region
enter partition(array, 2, 3)
1  //content of region 
enter choosePivot(array, 2, 3)
1  //content of region 
0  //content of region - WAIT, WHAT HAPPENED TO THE ONE
end choosePivot
0   //content of region
end partition

所以我们至少找到了问题的位置:choosePivot。当我们仔细查看该功能时,我最终意识到错误:

void choosePivot(int theArray[], int first, int last){
    //cerr << "enter choosePivot(array, " << first << ", " << last << ")\n";
    int mid = (last - first) / 2;
    if( (theArray[first] <= theArray[mid] &&
         theArray[mid] <= theArray[last]) ||
        (theArray[last] <= theArray[mid] &&
         theArray[mid] <= theArray[first]) ){

theArray[last]超出了界限,过了阵营的终点。您将一个完全随机且无效的数字交换到数组中,并将一个元素交换出数组。这似乎经常发生。这就是我们在测试大数字之前测试准确性的原因。

当我将theArray[last]更改为theArray[last-1]时,您的代码passes all of my tests。注意:

  • C ++库已经有std::swap
  • 你泄漏了所有记忆。将deletenew匹配或更好,请使用std::vector<int>