C++ 以下快速排序的实现是否相同?

C++ 以下快速排序的实现是否相同?,c++,algorithm,recursion,quicksort,C++,Algorithm,Recursion,Quicksort,我在一个网站上遇到了这些快速排序的实现,一个是递归的,另一个是使用辅助堆栈的迭代的。它们的配分函数是相同的 递归快速排序 我想的是,这些都不完全“相同”,因为第一部分从l到p-1递归地作用于第一部分,然后作用于第二部分,而另一部分则作用于从p+1到h的第二部分,第一部分和第一部分? 我这样想对吗 是的,你说得对。迭代解决方案首先对第二部分进行排序,然后对第一部分进行排序。在这种情况下,这并不重要,但如果是顺序遍历打印,那么顺序将造成严重破坏:D!只是一个小问题:intstack[h-l+1];创

我在一个网站上遇到了这些快速排序的实现,一个是递归的,另一个是使用辅助堆栈的迭代的。它们的配分函数是相同的

递归快速排序

我想的是,这些都不完全“相同”,因为第一部分从l到p-1递归地作用于第一部分,然后作用于第二部分,而另一部分则作用于从p+1到h的第二部分,第一部分和第一部分?
我这样想对吗

是的,你说得对。迭代解决方案首先对第二部分进行排序,然后对第一部分进行排序。在这种情况下,这并不重要,但如果是顺序遍历打印,那么顺序将造成严重破坏:D!只是一个小问题:intstack[h-l+1];创建可变长度数组。这在C++中是不允许的。最好使用std::stack。请注意,在大多数情况下,您都不想执行这两种操作。您需要检查哪个分区更小,并首先递归到那个分区。这将最坏情况下的堆栈深度限制为Olog N;对于您介绍的版本,这是最坏的情况。
/* A[] --> Array to be sorted, l  --> Starting index, h  --> Ending index */
void quickSort(int A[], int l, int h)
{
    if (l < h)
    {       
       int p = partition(A, l, h); /* Partitioning index */
       quickSort(A, l, p - 1); 
       quickSort(A, p + 1, h);
    }
}
* A[] --> Array to be sorted, l  --> Starting index, h  --> Ending index */
void quickSortIterative (int arr[], int l, int h)
{
    // Create an auxiliary stack
    int stack[ h - l + 1 ];

    // initialize top of stack
    int top = -1;

    // push initial values of l and h to stack
    stack[ ++top ] = l;
    stack[ ++top ] = h;

    // Keep popping from stack while is not empty
    while ( top >= 0 )
    {
        // Pop h and l
        h = stack[ top-- ];
        l = stack[ top-- ];

        // Set pivot element at its correct position in sorted array
       int p = partition( arr, l, h );

       // If there are elements on left side of pivot, then push left
       // side to stack
       if ( p-1 > l )
       {
           stack[ ++top ] = l;
           stack[ ++top ] = p - 1;
       }  

       // If there are elements on right side of pivot, then push right
       // side to stack
       if ( p+1 < h )
       {
           stack[ ++top ] = p + 1;
           stack[ ++top ] = h;
       }
   }
}