快速排序枢轴枢轴、快速

2023-09-08 09:55:14 作者:夜空中最亮的星

使用快速排序对以下数组 a 进行排序,

Sort the following array a using quicksort,

[6, 11, 4, 9, 8, 2, 5, 8, 13, 7]

主元应选择为第一个和最后一个元素的算术平均值,即(a[0] + a[size - 1])/2(向下取整).

The pivot should be chosen as the arithmetic mean of the first and the last element, i.e., (a[0] + a[size - 1]) / 2 (rounded down).

显示所有重要步骤,例如分区和对算法的递归调用.

Show all important steps such as partitioning and the recursive calls to the algorithm.

我了解如何使用快速排序对数组进行排序,但我不确定如何计算枢轴.

I understand how to sort the array using quicksort, however I'm not sure how to calculate the pivot.

枢轴是由 6 + 7 = 13 然后 13/2 = 6.5 计算出来的(向下舍入是 6)所以枢轴是2(即第6个元素)?

Is the pivot calculated by 6 + 7 = 13 then 13 / 2 = 6.5 (rounded down is 6) so the pivot is 2 (i.e. the 6th element)?

我知道小于pivot的元素出现在左侧,大于pivot的元素出现在右侧,分区重复这个对子数组排序的步骤.

I know the elements less than pivot appear on the left hand side, and elements greater than the pivot appear on the right hand side, and the partition repeats this step of sorting the sub-array.

任何帮助将不胜感激.

推荐答案

对于快速排序,枢轴可以是您想要的任何元素.查看 维基百科.

For quicksort, the pivot can be whatever element you want. Check out Wikipedia.

问题很容易解决,方法是选择一个随机索引作为枢轴,选择分区的中间索引或(尤其是对于较长的分区)选择枢轴分区的第一个、中间和最后一个元素的中位数

The problem was easily solved by choosing either a random index for the pivot, choosing the middle index of the partition or (especially for longer partitions) choosing the median of the first, middle and last element of the partition for the pivot

三个选择:

第一个元素中间元素第一个、中间和最后一个的中位数.

在你的情况下,使用第一个和最后一个元素的平均值 value 会给你:

And in you case using the mean of first and last element value would give you :

6 + 7 = 13
13 / 2 = 6.5
6.5 rounded down = 6