Quicksort Pivot
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
For the given array [6, 11, 4, 9, 8, 2, 5, 8, 13, 7]
Calculate something like this:
- Select first element which is
6
Select last element of list which is
7
Select mid element which is
mid = (length%2==0) ? (length/2)-1 : (length-1)/2
, which is8
- This makes an array and sort this it will be
[6,7,8]
, now mid element in your array is mid.
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.