排序算法—python

阅读更多

归并排序:

 

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:])
	else:
		c.extend(a[i:])
	return c

def merge_sort(lists):
	if len(lists) <= 1:
		return lists
	middle = len(lists)/2
	left_list = merge_sort(lists[:middle])
	right_list = merge_sort(lists[middle:])
	return merge(left_list, right_list)

 

 

 

堆排序:

 

def Max_Heapify(heap, heapSize, i):#在堆中做结构调整使得父节点的值大于子节点
	left = 2*i + 1
	right = 2*i + 2
	tmp = i
	if left < heapSize and heap[left] > heap[tmp]:
		tmp = left
	if right < heapSize and heap[right] > heap[tmp]:
		tmp = right
	if tmp != i:
		heap[tmp], heap[i] = heap[i], heap[tmp]
		Max_Heapify(heap, heapSize, tmp)	
		
def Build_Max_Heap(heap):#构造一个堆,将堆中所有数据重新排序
    for i in range(len(heap)/2, -1, -1):
		Max_Heapify(heap, len(heap), i)

def HeapSort(heap):#将根节点取出与最后一位做对调,对前面len-1个节点继续进行对调整过程。
    Build_Max_Heap(heap)
    for i in range(len(heap)-1, -1, -1):
		heap[0], heap[i] = heap[i], heap[0]
		Max_Heapify(heap, i, 0)
    return heap

 快速排序:

def QuickSort(arr, begin, end):
    if begin < end:
        tmp = Partition(arr, begin, end)
        QuickSort(arr, begin, tmp)       
        QuickSort(arr, tmp + 1, end)
    else:
        return
 
 
def Partition(arr, begin, end):
    i = begin - 1
    for j in range(begin, end):
        if arr[j] <= arr[end]:
            i = i + 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i+1], arr[end] = arr[end], arr[i+1]
    return i

 

 

你可能感兴趣的:(排序算法—python)