python實現排序演算法(一)——插入排序演算法

來源:互聯網
上載者:User

標籤:[]   資料   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實現排序演算法(一)——插入排序演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.