冒泡
import random
def maopao(list):
length = len(list)
for i in range(length-1,0,-1):
for j in range(i):
if list[j]>list[j+1]:
list[j],list[j+1] = list[j+1],list[j]
list = [i for i in range(100)]
random.shuffle(list)
maopao(list)
print(list)
插入
import random
def charu(list):
length = len(list)
for i in range(1,length):
position = i
currentVaule = list[position]
while position > 0 and list[position-1]>currentVaule:
list[position] = list[position-1]
position = position-1
list[position] = currentVaule
list = [i for i in range(100)]
random.shuffle(list)
charu(list)
print(list)
选择
import random
def xuanze(list):
length = len(list)
for i in range(length,1,-1):
max_index = 0
for j in range(i):
if list[j]>list[max_index]:
max_index = j
list[i-1],list[max_index] = list[max_index],list[i-1]
list = [i for i in range(100)]
random.shuffle(list)
xuanze(list)
print(list)
谢尔
import random
def charu(index,length,sublistcount):
for i in range(index,length,sublistcount):
position = i
currentVaule = list[position]
while position > 0 and list[position - 1] > currentVaule:
list[position] = list[position - 1]
position = position - 1
list[position] = currentVaule
def xier(list):
length = len(list)
sublistcount = len(list) // 2
while sublistcount > 0:
for index in range(sublistcount):
charu(index,length,sublistcount)
sublistcount = sublistcount // 2
list = [i for i in range(100)]
random.shuffle(list)
xier(list)
print(list)
归并
import random
def guibing(list):
if len(list) == 1:
return list
middle = len(list) // 2
left = guibing(list[:middle])
right = guibing(list[middle:])
merged = []
while left and right:
if left[0]<right[0]:
merged.append(left.pop(0))
else:
merged.append(right.pop(0))
merged.extend(left if left else right)
return merged
list = [i for i in range(100)]
random.shuffle(list)
list = guibing(list)
print(list)
快速
import random
def kuaisu(list):
quickSortHelper(list,0,len(list)-1)
def quickSortHelper(list,first,last):
if first<last:
splitpoint = partition(list,first,last)
quickSortHelper(list, first, splitpoint-1)
quickSortHelper(list, splitpoint+1, last)
def partition(list,first,last):
pivotvalue = list[first]
leftmark = first+1
rightmark = last
finish = False
while not finish:
while leftmark <= rightmark and list[leftmark] < pivotvalue:
leftmark += 1
while leftmark <= rightmark and list[rightmark] > pivotvalue:
rightmark -= 1
if leftmark > rightmark:
finish = True
else:
list[leftmark],list[rightmark] = list[rightmark],list[leftmark]
list[first], list[rightmark] = list[rightmark], list[first]
return rightmark
list = [i for i in range(100)]
random.shuffle(list)
kuaisu(list)
print(list)