目录
[排序]
归并排序
#归并
def mSort(nums): #分为两个列表,分别排序
if len(nums)<=1:
return nums
else:
m = len(nums)//2
print 'len(nums): ',len(nums)
print 'nums: ',nums
print 'm: ',m
left = mSort(nums[:m])
right = mSort(nums[m:])
ret = merge(left,right)
return ret
def merge(left,right):#合并两个列表
i = 0
j = 0
k = 0
ret =[]
print '--------'
print 'left: ',left
print 'right: ',right
while i<len(left) and j< len(right):
if left[i]<right[j]:
ret.append(left[i])
i += 1
else:
ret.append(right[j])
j += 1
ret += left[i:]
ret += right[j:]
return ret
快速排序:
#快排、
def quickSort(nums):
qSort(nums,0,len(nums)-1)
def qSort(nums,low,high):
if low<high:
pivot = partition(nums,low,high)
qSort(nums,low,pivot-1)#低位排序
qSort(nums,pivot+1,high)#高位排序
def partition(nums,low,high):#枢纽点
pivotkey = nums[low]
while low<high:
while low<high and nums[high]>=pivotkey:
high -= 1
nums[low],nums[high] = nums[high],nums[low]
while low<high and nums[low]<=pivotkey:
low += 1
nums[low],nums[high] = nums[high],nums[low]
return low