地精排序:
#! /usr/bin/env python
#coding=utf-8
import random
def gnomesort(lst):
i = 0
while i < len(lst):
if i == 0 or lst[i-1] <= lst[i]:
i += 1
else:
lst[i], lst[i-1] = lst[i-1], lst[i]
i -= 1
def main():
lst = [random.randint(1,20) for i in range(10)]
print(lst)
gnomesort(lst)
print(lst)
if __name__ == "__main__":
main()
冒泡排序:
#! /usr/bin/env python
#coding=utf-8
import random
def bubble_sort_raw(seq):
pass_cnt = len(seq) - 1
for i in range(pass_cnt):
for j in range(len(seq)-i-1):
if seq[j] > seq[j + 1]:
seq[j], seq[j+1] = seq[j+1], seq[j]
def bubble_sort_adv(seq):
pass_cnt = len(seq) - 1
exchanged = True
while pass_cnt > 0 and exchanged:
exchanged = False
for i in range(pass_cnt):
if seq[i] > seq[i+1]:
exchanged = True
seq[i],seq[i+1] = seq[i+1],seq[i]
pass_cnt = pass_cnt - 1
if __name__ == '__main__':
seq = [random.randint(0,20) for i in range(10)]
print(seq)
bubble_sort_raw(seq)
print(seq)
seq = [random.randint(0,20) for i in range(10)]
print(seq)
bubble_sort_adv(seq)
print(seq)
选择排序:
#! /usr/bin/env python
#coding=utf-8
import random
def select_sort(lst):
pass_cnt = len(lst) - 1
for i in range(pass_cnt):
pos_of_min = i
for j in range(i+1,pass_cnt+1):
if lst[j] < lst[pos_of_min]:
pos_of_min = j
if pos_of_min != i:
lst[i],lst[pos_of_min] = lst[pos_of_min],lst[i]
def select_sort_rec(lst,i):
#select sort recursive version
if i == 0: return
pos_of_max = i
for j in range(i):
if lst[j] > lst[pos_of_max]:
pos_of_max = j
lst[i],lst[pos_of_max] = lst[pos_of_max],lst[i]
select_sort_rec(lst,i-1)
if __name__ == "__main__":
lst = [random.randint(0,20) for i in range(10)]
print(lst)
select_sort(lst)
print(lst)
lst = [random.randint(0,20) for i in range(10)]
print(lst)
select_sort_rec(lst,len(lst)-1)
print(lst)
插入排序:
#! /usr/bin/env python
#coding=utf-8
import random
def ins_sort(lst):
for i in range(1,len(lst)):
pivot = lst[i]
while (i > 0 and lst[i-1] > pivot):
lst[i] = lst[i-1]
i = i - 1
lst[i] = pivot
def ins_sort_binarysearch(lst):
for i in range(1,len(lst)):
pivot = lst[i]
low = 0
high = i - 1
while (low <= high):
mid = (high + low) >> 1
if lst[mid] > pivot:
high = mid - 1
else:
low = mid + 1
while (i > low):
lst[i] = lst[i-1]
i = i - 1
lst[low] = pivot
def ins_sort_rec(lst,i):
if i == 0: return
ins_sort_rec(lst,i-1)
j = i
while j > 0 and lst[j-1] > lst[j]:
lst[j-1],lst[j] = lst[j],lst[j-1]
j = j - 1
if __name__ == '__main__':
lst = [random.randint(0,20) for i in range(10)]
lst2 = lst[:]
lst2.sort()
print(lst)
ins_sort(lst)
print(lst2)
print(lst)
lst = [random.randint(0,20) for i in range(10)]
lst2 = lst[:]
print(lst)
lst2.sort()
print(lst2)
ins_sort_binarysearch(lst)
print(lst)