为什么quicksort需要对“ sorted”小节进行递归?

时间:2018-11-21 21:33:10

标签: java algorithm sorting

对于alg /数据结构来说,它还是很新的东西,它一直在尝试学习如何应用快速排序。

我找到了以下实现:https://www.geeksforgeeks.org/quick-sort/

让我感到困惑的部分:

/* The main function that implements QuickSort() 
      arr[] --> Array to be sorted, 
      low  --> Starting index, 
      high  --> Ending index */
    void sort(int arr[], int low, int high) 
    { 
        if (low < high) 
        { 
        /* pi is partitioning index, arr[pi] is  
          now at right place */
        int pi = partition(arr, low, high); 

        // Recursively sort elements before 
        // partition and after partition 
        sort(arr, low, pi-1); 
        sort(arr, pi+1, high); 
    } 
} 

在我看来,我们不必遍历sort(arr,low,pi-1)部分,因为该算法应该已经对该部分进行了排序...

1 个答案:

答案 0 :(得分:0)

在实施quicksort时,我在某些地方进行了注释,以使您更清楚地了解quicksort的思想。在您使用pi函数计算变量partition的代码中,索引pi之前的所有元素均小于arr[pi],但不能保证这些元素按排序顺序排列。同样,索引pi之后的所有元素都大于arr[pi],但不能保证这些元素按排序顺序排列。我已在您的以下代码中将其注释掉:

int partition (arr[], low, high)
{
   // pivot (Element to be placed at right position)
   pivot = arr[high];  
   i = (low - 1)  // Index of smaller element
   for (j = low; j <= high- 1; j++)
   {
    // If current element is smaller than or equal to pivot
    /* But, it does not guaranteed that smaller elements will come in sorted fashion*/
    if (arr[j] <= pivot)
    {
        i++;    // increment index of smaller element
        swap arr[i] and arr[j]
     }
   }
   swap arr[i + 1] and arr[high])
   return (i + 1)
 }

/* The main function that implements QuickSort() 
  arr[] --> Array to be sorted, 
  low  --> Starting index, 
  high  --> Ending index */
 void sort(int arr[], int low, int high) 
 { 
    if (low < high) 
    { 
    /* pi is partitioning index, arr[pi] is  
      now at right place */
     int pi = partition(arr, low, high); 
     /*Here, all the elements before index pi are less than arr[pi] but 
       not guaranteed that they are in sorted order.
       Also, all the elements after index pi are greater than arr[pi] but 
       not guaranteed to be in sorted order.
     */
     // Recursively sort elements before 
     // partition and after partition 
     sort(arr, low, pi-1); 
     sort(arr, pi+1, high); 
  } 
}