用Python练习写一些常用的排序算法
# -*- coding:utf-8 -*-
"""
选择排序
"""
def selectSort(arr):
print('this is select sort')
for i in range(0, len(arr)):
min = arr[i]
index = i
for j in range(i + 1, len(arr)):
if(arr[j] < min):
min = arr[j]
index = j
arr[index] = arr[i]
arr[i] = min
"""
冒泡排序
"""
def insertSort(arr):
print('this is insert sort')
for i in range(0, len(arr)):
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
t = arr[i]
arr[i] = arr[j]
arr[j] = t
"""
快速排序
"""
def quickSort(arr, left, right):
if left >= right:
return
i = left
j = right
key = arr[left]
while i < j:
# j向左走,直到找到一个小于key的元素
while i < j and arr[j] >= key:
j -= 1
if i < j:
arr[i] = arr[j]
i += 1
# i向右走,直到找到一个大于key的元素
while i < j and arr[i] <= key:
i += 1
if i < j:
arr[j] = arr[i]
j -= 1
arr[i] = key
quickSort(arr, left, i - 1)
quickSort(arr, i + 1, right)
"""
归并排序
"""
def mergeSort(arr, start, end):
if start < end:
mid = (int)((start + end) / 2)
mergeSort(arr, start, mid)
mergeSort(arr, mid + 1, end)
merge(arr, start, mid, mid + 1, end)
def merge(arr, s1, e1, s2, e2):
i = s1
j = s2
list = []
while i <= e1 and j <= e2:
if arr[i] <= arr[j]:
list.append(arr[i])
i += 1
else:
list.append(arr[j])
j += 1
while i <= e1:
list.append(arr[i])
i += 1
while j <= e2:
list.append(arr[j])
j += 1
for i in range(s1, max(e1, e2)+1):
arr[i] = list[i-s1]
"""
堆排序
构建一个小顶堆,父节点的值小于孩子节点
假设我们需要从海量的数据中找到前k大的数,最好的方法是构建小顶堆
首先用前k个数构建一个小顶堆,然后遍历剩余的数
如果此数 < 堆顶元素,说明比k个数中的最小值还小,则直接跳过此数,遍历下一个
如果此数 > 堆顶元素,则将此数和堆顶交换,然后从堆顶向下调整
"""
class MinHeap(object):
__max_size = 0; #堆的大小
heap_list = []
# 创建堆
def create_heap(self, arr):
self.heap_list = arr
n = len(self.heap_list)
for i in range(int(n / 2) - 1, -1, -1):
self.fix_down(i, n-1)
# 取出堆顶元素
def get_top(self):
if len(self.heap_list) > 0:
return self.heap_list[0]
return None
# 向下调整堆
def fix_down(self, a, end):
last = end
child = a * 2 + 1 #当前节点的左孩子
temp = self.heap_list[a]
while child <= last:
# 选出两个孩子中较小的那个
if child < last and self.heap_list[child+1] < self.heap_list[child]:
child += 1
if temp < self.heap_list[child]:
break
else:
# 孩子节点覆盖当前节点
self.heap_list[a] = self.heap_list[child]
a = child
child = child * 2 + 1
self.heap_list[a] = temp
print(self.heap_list)
# 堆排序,取出堆顶元素,与最后一个元素交换,调整堆
def heap_sort(self):
n = len(self.heap_list) - 1
for i in range(n, -1, -1):
temp = self.heap_list[i]
self.heap_list[i] = self.heap_list[0]
self.heap_list[0] = temp
self.fix_down(0, i-1)
return self.heap_list
def heapSort(arr):
m = MinHeap()
m.create_heap(arr)
print('开始排序')
return m.heap_sort()
arr = [19, 17, 20, 18, 16, 21]
# selectSort(arr)
# insertSort(arr)
# quickSort(arr, 0, len(arr) - 1)
# mergeSort(arr, 0, len(arr) - 1)
heapSort(arr)
# print(arr)
# print(arr)