Quicksort Pivot

非 Y 不嫁゛ 提交于 2019-11-28 12:12:48

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

Three choices thus :

  • First element
  • Middle element
  • Median of first, middle and last.

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

By the way the question is worded, the pivot should just be 6 and not necessarily the 6th item in the array.

This is most definitely the case because if there were only 3 items in the array, for example, and the arithmetic mean came out to be greater than 3, you would have no pivot to choose because there is no item with that index.

Note: Be careful with the way you index elements in your array. You said the 6th element is '2', when it may be '5' if your programming language starts indices at 0.

Your pivot is 6. Your pivot is NOT the 6th element Now you can apply the following algorith.

function quicksort(array)
 var list less, greater
 if length(array) ≤ 1
     return array  // an array of zero or one elements is already sorted
 select and remove a pivot value pivot from array
 for each x in array
     if x ≤ pivot then append x to less
     else append x to greater
 return concatenate(quicksort(less), pivot, quicksort(greater))

The position of the pivot from that calculation is not important, quicksort sorts the elements based on whether they are more or less than the pivot. Then the pivot is placed in between the two sets (more and less).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!