使用中间元素作为枢轴快速排序

时间:2015-01-11 10:41:39

标签: quicksort

我对快速排序的理解是

  1. 选择一个枢轴元素(在这种情况下,我选择中间元素为 枢轴)
  2. 在极端情况下初始化左右指针。
  3. 找到枢轴左侧的第一个元素,该元素大于数据透视。
  4. 同样找到小于枢轴
  5. 的枢轴右侧的第一个元素
  6. 交换3和4中找到的元素。
  7. 重复3,4,5除非左> gt; =右。
  8. 对于左右子阵列重复整个过程,因为现在将枢轴置于其位置。
  9. 我确信我在这里错过了一些非常愚蠢的东西。但上面似乎没有工作到这个阵列:

      8,7,1,2,6,9,10,2,11 pivot: 6  left pointer at 8, right pointer at 11
      2,7,1,2,6,9,10,8,11 swapped 2,8  left pointer at 7, right pointer at 10
    

    现在怎样?它的右侧没有小于6的元素。  7将如何进入6的右边?

3 个答案:

答案 0 :(得分:4)

左侧和右侧之间没有前期划分。特别是,6不是分裂。相反,除法是将左右指针移动到彼此更近的结果,直到它们相遇为止。结果可能是一方比另一方小得多。

您对算法的描述很好。没有任何地方说你必须停在中间元素。继续按照给定的方式执行它。

BTW。:在排序过程中可能会移动枢轴元素。即使它被移动,也要继续与6进行比较。

<强>更新

您对算法的描述确实存在一些小问题。一个是步骤3或步骤4需要包含等于的元素到枢轴。让我们像这样重写:

我对快速排序的理解是

  1. 选择一个轴心值(在这种情况下,选择中间元素的值)
  2. 在极端情况下初始化左右指针。
  3. 从左指针开始向右移动,找到第一个大于或等于数值的元素。
  4. 同样,从右指针开始向左移动,找到第一个元素,即 小于透视值
  5. 交换3和4中的元素。
  6. 重复3,4,5,直到左指针大于或等于右指针。
  7. 对左指针左侧和右侧的两个子阵列重复整个过程。
  8. pivot value: 6, left pointer at 8, right pointer at 11
    8,7,1,2,6,9,10,2,11 left pointer stays at 8, right pointer moves to 2
    2,7,1,2,6,9,10,8,11 swapped 2 and 8, left pointer moves to 7, right pointer moves to 2
    2,2,1,7,6,9,10,8,11 swapped 2 and 7, left pointer moves to 7, right pointer moves to 1
    pointers have now met / crossed, subdivide between 1 and 7 and continue with two subarrays
    

答案 1 :(得分:0)

Quick Sort Given an array of n elements (e.g., integers):
-If array only contains one element, return
-Else
  pick one element to use as pivot.
  Partition elements into two sub-arrays:
    Elements less than or equal to pivot
    Elements greater than pivot
  Quicksort two sub-arrays
  Return results

Let i and j are the left and right pivots, then code for one array will look like this:

1) While data[i] <= data[pivot]
    ++i
2) While data[j] > data[pivot]
    --j
3) If i < j
    swap data[i] and data[j]
4) While j > i, go to 1.
5) Swap data[j] and data[pivot_index]

Position of index j is where array is to-be partitioned in two half and then same steps are applied to them recursively.

最后,您得到一个排序的数组。

答案 2 :(得分:0)

您的困惑是因为您认为分区应该是分隔两者的地标。这是不正确的(对于中间元素枢轴)!

  • Lomuto的分区(枢轴=最右边的分区)。 左:(lo ... p-1) (请注意不包括支点) 右:(p + 1 ...高)
  • 中间元素作为枢轴。该段已分区: 左:(lo ... p) 右:(p + 1 ...高) [https://en.wikipedia.org/wiki/Quicksort]
相关问题