1.插入排序
這種方法思路是有一個空數組每次按大小將數據插入進去(放到數組最後,或者與數組中成員交換位置之後成員都向後移動),到最後就可以得到一個按順序排列的數組,這裏用Python加以實現(降序排列)
def sort(x):
for i in range(2,len(x)):
key=x[i]
j=i-1
while i>0 and x[j]>key:
x[j+1]=x[j]
j=j-1
x[j+1]=key
return x
可以計算出增長量級爲O(n^2)
2.選擇排序
這種算法思路更爲直接,找到數組中最大的元素放在數組第0位,第二大的元素放在數組第1位.....
這裏用Python實現(降序排列)
def choose(x):
count=0
y=[]
for num in range(len(x)):
y.append(0)
for i in range(len(x)):
for j in range(len(x)):
if i != j and x[i]<x[j]:
count+=1
y[count]=x[i]
count=0
return y
#算法分析
#算法思路
def gaijin(x):
temp=0 #1
count=0 #1
for i in range(len(x)): #x
for j in range(len(x)): #x^2
if i != j and x[i]<x[j]: #x(x-1)
count+=1 #y
temp=x[count] #x-1
x[count]=x[i] #x-1
x[i]=temp #x-1
count=0 #x-1
return x #1
from random import *
x=[1,2,3,4,5]
shuffle(x)
print(x)
第一個函數需要新建一個列表 改進後不再需要建立新的列表
計算出2增長量級O(n^2)