標籤:[] 資料 def 排序 rand temp 第一個 dex name
1 ‘‘‘ 2 插入排序演算法 3 未經處理資料data 4 排序資料後資料SortedData,預設是從小打大排序 5 6 1.從data第一個元素開始,該元素賦值給SortedData[0],可以認為SortedData已經被排序 7 8 2.取出data的一個元素data[i], 9 (1)從左至右掃描SortedData,10 如果data[i]小於SortedData的某個元素SD,那麼將data[i]插入SD的位置,選取下一個元素11 (1)如果data[i]大於SortedData最後一個元素,將data[1]插入到SortedData的末尾,選取下一個元素12 13 3.重複步驟214 ‘‘‘15 16 #/usr/bin/env python17 #coding:utf-818 #__author__= “livermorium116”19 20 21 import random 22 import time23 class InsertionSorted():24 def __init__(self):25 self.data=self.dataRand()26 27 self.SortedData=[self.data[0]]#預設獲得第1個元素,28 print(‘排序前:‘)29 print(‘__________________‘)30 self.SortedByInsertion()31 32 def SortedByInsertion(self):33 TimeCount=time.time() ##程式計時34 TimeCountCPU=time.clock()##CPU計時35 36 for D in self.data[1:]: ##從餘下的元素選取37 for SD in self.SortedData: ##選取已排序元素中的一個SD38 if D < SD: 39 tem=self.SortedData.index(SD)40 self.SortedData.insert(tem,D)41 print(self.SortedData)42 break43 選取下一元素44 45 if D >= self.SortedData[-1]: ##比較最後一個元素46 self.SortedData.append(D)47 print(self.SortedData)48 continue 49 50 51 TimeCountCPU=time.clock()-TimeCountCPU52 TimeCount=time.time()-TimeCount53 54 print(‘排序後:\n‘)55 print(self.SortedData)56 print("總排序用時%4f\nCPU用時%4f\n"%(TimeCount,TimeCountCPU))57 def dataRand(self):58 temp=[]59 for i in range(10):60 temp.append(random.randint(1,100))61 print(temp)62 print("_____________")63 return temp64 65 66 if __name__ =="__main__":67 68 IS=InsertionSorted()69 70
python實現排序演算法(一)——插入排序演算法