快速排序
def quicksort(nums, start, end):
if start >= end: return
mid = nums[start]
low, high = start, end
while low < high:
while low < high and nums[high] >= mid:
high -= 1
nums[low] = nums[high]
while low < high and nums[low] < mid:
low += 1
nums[high] = nums[low]
nums[low] = mid
quicksort(nums, start, low - 1)
quicksort(nums, low + 1, end)
return nums
利用快速排序的思想找中位数
def findmedian(nums):
def quickfind(nums, k, start, end):
key = nums[start]
low, high = start, end
while low < high:
while low < high and nums[high] >= key:
high -= 1
nums[low] = nums[high]
while low < high and nums[low] < key:
low += 1
nums[high] = nums[low]
nums[low] = key
if low == k:
return low
elif low > k:
return quickfind(nums, k, start, low - 1)
else:
return quickfind(nums, k, low + 1, end)
if not nums or len(nums) == 0:
return -1
n = len(nums)
if n % 2 == 0:
a = quickfind(nums, n // 2, 0, n - 1)
b = quickfind(nums, n // 2 - 1, 0, n - 1)
return (nums[a] + nums[b]) / 2.0
else:
x = quickfind(nums, n // 2, 0, n - 1)
return nums[x]