排序
一、快速排序
def quick_sort(arry): if len(arry)<=1: return arry target = arry[0] left, right = [], [] i = 1 while i < len(arry): if arry[i] <= target: left.append(arry[i]) else: right.append(arry[i]) i += 1 return quick_sort(left) + [target] + quick_sort(right)
def get_index(nums,begin,end): i,j = begin,end-1 while i<j: while i<j and nums[i]<=nums[end]: i+=1 while i<j and nums[j]>=nums[end]: j-=1 nums[i],nums[j] = nums[j],nums[i] if nums[end]<nums[i]: nums[i],nums[end] = nums[end],nums[i] return i def quick_sort(nums,begin,end): if begin<end: index = get_index(nums,begin,end) quick_sort(nums,begin,index) quick_sort(nums,index+1,end)
二、归并排序
def merge(a,b): c = [] i,j=0,0 while i<len(a) and j<len(b): if a[i]<=b[j]: c.append(a[i]) i+=1 else: c.append(b[j]) j+=1 if i==len(a): c.extend(b[j:]) if j==len(b): c.extend(a[i:]) return c def merge_sort(arry): if len(arry)<=1: return arry mid = len(arry)//2 left = merge_sort(arry[:mid]) right = merge_sort(arry[mid:]) return merge(left,right)