def bubble_sort(array):
n = len(array)
for i in range(n):
already_sorted = True
for j in range(n-i-1):
if array[i] > array[i+1]:
array[i],array[i+1] = array[i+1],array[i]
already_sorted = False
if already_sorted:
break
n = len(array)
for index in range(n):
for i in range(index,n):
if array[index] > array[i]:
array[index],array[i] = array[i],array[index]
def insert_sort(array):
n = len(array)
for i in range(n):
temp = array[i]
for j in range(i-1,-1,-1):
if array[j] <= temp:
break
if array[j] > temp:
array[j],array[j+1] = temp,array[j]
def shell_sort(array):
length = len(array)
dist = length/2
while dist>0:
for i in range(dist,length):
temp = list[i]
j = i
while j>=dist and temp < list[j-dist]:
list[j] = list[j-dist]
j -= dist
list[j] = temp
dist /=2
return array
def merge(list1,list2):
length_list1 = len(list1)
length_list2 = len(list2)
if length_list1 == 0:
return list2
if length_list2 == 0:
return list1
result = []
index_list1 = index_list2 = 0
while len(result) < length_list1+length_list2:
if list1[index_list1] <= list2[index_list2]:
result.append(list1[index_list1])
index_list1 += 1
else:
result.append(list2[index_list2])
index_list2 += 1
if index_list1 == length_list1:
result.extend(list2[index_list2:])
break
if index_list2 == length_list2:
result.extend(list1[index_list1:])
break
return result
def merge_sort(array):
if len(array) <2:
return array
midpoint = len(array)//2
return merge(merge_sort(array[:midpoint]),merge_sort(array[midpoint:]))
from random import randint
def quicksort(array):
if len(array) < 2:
return array
low,same,high = [],[],[]
pivot = array[randint(0,len(array)-1)]
for i in range(len(array)):
if array[i] < pivot:
low.append(array[i])
elif array[i] == pivot:
same.append(array[i])
else:
high.append(array[i])
return quicksort(low) + same + quicksort(high)
def head_sort(array):
length = len(array)
first = int(length/2 -1)
for start in range(first,-1,-1):
max_heapify(array,start,length-1)
for end in range(length-1,0,-1):
array[0],array[end] = array[end],array[0]
max_heapify(array,0,end-1)
return array
def max_heapify(list,start,end):
root = start
while True:
child = root*2 + 1
if child > end:
break
if child + 1 <=end and list[child] < list[child+1]:
child = child + 1
if list[child] > list[root]:
list[root],list[child] = list[child],list[root]
root = child
else:
break
def radix_sort(array):
i = 0
max_num = max(array)
j = len(str(max_num))
while i<j:
bucket_list = [[] for _ in range(10)]
for item in array:
bucket_list[int(item/(10**i))%10].append(item)
array.clear()
for bucket in bucket_list:
for item in bucket:
array.append(item)
i += 1
return array
十大排序