数据结构排序算法python版本
# coding=utf-8
# 冒泡排序,两两对比,进行交换位置
def pupple_sort(arr):
for i in range(len(arr)):
for j in range(len(arr)):
if arr[j] < arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
# 插入排序,依次取若干量的数据进行选择最大的插入当前位置
def insert_sort(arr):
for i in range(len(arr)):
for j in range(0,i):
if arr[j] < arr[i]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print(arr)
# 希尔排序,插入排序升级版本
def shell_sort(arr):
ng = int(len(arr)/2)
while ng>=1:
for i in range(0,len(arr)-ng,1):
for j in range(i,i+ng+1,1):
if arr[j] < arr[i]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
ng = int(ng/2)
print(arr)
# 选择排序,每次循环在当前序列中选取最值放在当前位置
def select_sort(arr):
for i in range(len(arr)):
min = arr[i]
for j in range(i,len(arr),1):
if min > arr[j]:
temp = arr[j]
arr[j] = min
min = temp
arr[i] = min
print(arr)
def adjust_heap(arr,i,length):
# 构建大根堆或者小根堆
start = i*2+1
temp = arr[i]
while start<length:
if start+1<length and arr[start] < arr[start+1]:
start+=1
if arr[start] > temp:
arr[i],arr[start] = arr[start],arr[i]
i = start
else:
break
start = start*2+1
# 堆排序
def heap_sort(arr):
# 构建初始大根堆或者小根堆
for i in range(int(len(arr)/2-1),-1,-1):
adjust_heap(arr,i,len(arr))
# 交换位置,再次构建大根堆或小根堆
for j in range(len(arr)-1,0,-1):
arr[0],arr[j] = arr[j],arr[0]
adjust_heap(arr,0,len(arr))
print(arr)
def get_index(arr,low,high):
# 获取temp的正确位置并插入
temp = arr[low]
while low < high:
while low<high and arr[high] > temp:
high-=1
arr[low] = arr[high]
while low<high and arr[low] < temp:
low+=1
arr[high] = arr[low]
arr[low] = temp
return low
# 快速排序
def quick_sort(arr,low=0,high=None):
if high==None:
high = len(arr)-1
if low<high:
index = get_index(arr,low,high)
quick_sort(arr,low,index-1)
quick_sort(arr,index+1,high)
print(arr)
if __name__ == '__main__':
arr = [4,6,8,5,9]
# pupple_sort(arr)
# insert_sort(arr)
# shell_sort(arr)
# select_sort(arr)
# heap_sort(arr)
# quick_sort(arr)