快速排序
应该是数据结构中排序中最重要的一个,包括其中的patition思想,以及后面的整体的分治思想,都对于解决实际问题有很大的借鉴。快速排序是一种交换排序的方法,不稳定,也就是说如果两个相同的数,快排之后二者可能交换位置。
1.首先来看partition函数,函数名partition(data, l, r),在data[l,r]中找到第l个数的位置i,使得i左侧的数都小于该数,i右侧的数都大于该数,并返回位置i
def partition(data, l, r): i = l j = r x = data[i] while i<j: while i<j&data[j]>x: j -= 1 if i<j: data[i] = data[j] i += 1 while i<j&data[i]<x: i += 1 if i<j: data[j] = data[i] j -= 1 data[i] = x return i
2.然后对整个数组分治递归操作即可
def qsort(data, l, r): if l<r: i = partition(data, l, r) qsort(data, l, i-1) qsort(data, i+1, r) def quicksort(data): qsort(data, 0, len(data)-1)
归并排序:
def mergearray(nums, first, mid, last): tmp = [] mid2 = mid + 1 k = 0 while first<=mid and mid2<=last: if nums[first]<nums[mid2]: tmp[k] = nums[first] first += 1 else: tmp[k] = nums[mid2] mid2 += 1 k += 1 while first<=mid: tmp[k] = nums[first] first += 1 k += 1 while mid2<=last: tmp[k] = nums[mid2] mid2 += 1 k += 1 for i in range(k): nums[first+i] = tmp[i] def mergesort(nums, first, last): if first<last: mid = first + (last-first)/2 mergesort(nums,first, mid) mergesort(nums, mid+1, last) mergearray(nums, first, mid, last) def msort(nums): mergesort(nums, 0, len(nums)-1)
堆排序
def heapAdjust(nums, i): lchild = 2*i+1 rchild = 2*i+2 max = i if i <= len(nums)/2: if lchild<=len(nums) and nums[lchild]>nums[max]: max = lchild if rchild<=len(nums) and nums[rchild]>nums[max]: max = rchild if max != i: nums[max], nums[i] = nums[i], nums[max] def buildHeap(nums): i = len(nums)/2 while i >=0: heapAdjust(nums,i) def headSort(nums): buildHeap(nums) i = len(nums) - 1 while i>=0: nums[i], nums[0] = nums[0], nums[i] heapAdjust(nums[:-1],0)