median of three values strategy

前端 未结 8 1625
粉色の甜心
粉色の甜心 2020-11-29 23:08

What is the median of three strategy to select the pivot value in quick sort?

I am reading it on the web, but I couldn\'t figure it out what exactly it is? And also

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 23:43

    An implementation of Median of Three I've found works well in my quick sorts.

    (Python)
    # Get the median of three of the array, changing the array as you do.
    # arr = Data Structure (List)
    # left = Left most index into list to find MOT on.
    # right = Right most index into list to find MOT on
    
    def MedianOfThree(arr, left, right):
        mid = (left + right)/2
        if arr[right] < arr[left]:
            Swap(arr, left, right)        
        if arr[mid] < arr[left]:
            Swap(arr, mid, left)
        if arr[right] < arr[mid]:
            Swap(arr, right, mid)
        return mid
    
    # Generic Swap for manipulating list data.
    def Swap(arr, left, right):
        temp = arr[left]
        arr[left] = arr[right]
        arr[right] = temp    
    

提交回复
热议问题