1.插入排序
def insert_sort_method(l):#l为带排序数组
for i in range(1,len(l)):
key = l[i]
j=i-1
while j>=0 and l[j]>key:
l[j+1]=l[j]
j=j-1
l[j+1]=key
print(l)
2.希尔排序
def shell_sort_method(l):
part = int(len(l)/2)
while part>0:
for i in range(part,len(l)):
key = l[i]
j=i-part
while j>=0 and l[j]>key:
l[j+part]=l[j]
j=j-part
l[j+part]=key
part = int(part/2)
print(l)
通过调整part来控制希尔排序的间隔选择
3.堆排序
def heap_sort_method(l):#l为待排序数组
for i in range(0,len(l)):#对于第i次获取堆顶元素
build_heap(l, i)#执行建堆函数
l[0],l[len(l)-i-1] = l[len(l)-i-1],l[0]#将堆顶元素放置在数组末尾
print(l)
def build_heap(l,index):
n=(len(l)-index-2)>>1#最后一个需要调整的节点
for i in range(n,-1,-1):#对于每一个需要进行调整的节点
childPosition = (i<<1)+1#获取节点的左子节点
if childPosition+1<len(l)-index and l[childPosition]<l[childPosition+1]:#如果存在右子节点,则先与右子节点比较
childPosition += 1
if l[childPosition]>l[i]:#将父节点与子节点中较大的数放在父节点位置
l[i],l[childPosition]=l[childPosition],l[i]
4.快速排序
def quick_sort_method(l,low,high): #外部调用时传入:带排序数组,0,数组长度-1
if not low<high :
return
partition_index = partition(l,low,high)
quick_sort_method(l, low, partition_index-1)
quick_sort_method(l, partition_index+1, high)
print(l)
def partition(l,low,high):
key = l[low]
while low < high:
while low < high and l[high]>=key:
high-=1
l[low]=l[high]
while low < high and l[low]<key:
low+=1
l[high]=l[low]
l[low]=key
return low
5归并排序
def merge_sort_method(l):
n=1
while n<len(l):
for i in range(0,len(l),2):
if n*i>=len(l):
break
merge(l,i,n)
n=n<<1
def merge(l,i,n):
start_i1 = i*n
start_i2 = n*(i+1)
j1,j2,=start_i1,start_i2
t = []
while j1<start_i2 and j2<len(l) and j2<n*(i+2):
if l[j1]<=l[j2]:
t.append(l[j1])
j1+=1
else:
t.append(l[j2])
j2+=1
else:
while j2<len(l) and j2<n*(i+2):
t.append(l[j2])
j2+=1
while j1<start_i2 and j1<len(l):
t.append(l[j1])
j1+=1
l[start_i1:start_i1+len(t)]=t[:]