插入排序
插入排序的基本操作,是将一个数据插入有序的数据序列中,从而得到一个新的有序的序列。
算法的实现可看成,将数据列表分为两部分,第一部分已经排好序,把第二部分的每个数据逐次插入,每步插入已排序的文档,直至全部插入为止。
class insertSort:
list = []
def __init__(self,list):
self.list = list
def sort(self):
length = len(self.list)
for i in range(1,length):
if self.list[i]<self.list[i-1] :
temp = self.list[i]
index =i
while index>0 and self.list[index-1]>temp :
self.list[index]=self.list[index-1]
index-=1
self.list[index]=temp
print(self.list)
a= [3, 4, 1, 6, 2, 9, 7, 0, 8, 5]
myList = insertSort.insertSort(a)
myList.sort()
冒泡排序
冒泡排序的基本思想是,每次比较相邻的元素,如果顺序错误,交换位置。每一趟比较,将一个元素归为,如果有n个数,则需要归位置n个元素,即进行n-1次操作。缺点是效率很低。
class bubbleSort:
list=[]
def __init__(self,list):
self.list = list
def sort(self):
length = len(self.list)
for i in range(length):
for j in range(length-1-i):#第二层for循环需要有i,否则不会嵌套
index = j
if self.list[index] > self.list[index+1] :#升序排列
temp = self.list[index]
self.list[index]=self.list[index+1]
self.list[index+1]=temp
print(self.list)
a= [3, 4, 1, 6, 2, 9, 7, 0, 8, 5]
myList = bubbleSort.bubbleSort(a)
myList.sort()