Python實現的基數排序演算法原理與用法執行個體分析,python執行個體分析

來源:互聯網
上載者:User

Python實現的基數排序演算法原理與用法執行個體分析,python執行個體分析

本文執行個體講述了Python實現的基數排序演算法。分享給大家供大家參考,具體如下:

基數排序(radix sort)屬於“分配式排序”(distribution sort),又稱“桶子法”(bucket sort)或bin sort,顧名思義,它是透過索引值的部份資訊,將要排序的元素分配至某些“桶”中,藉以達到排序的作用,基數排序法是屬於穩定性的排序,其時間複雜度為O (nlog(r)m),其中r為所採取的基數,而m為堆數,在某些時候,基數排序法的效率高於其它的穩定性排序法。

實現代碼如下:

#-*- coding: UTF-8 -*-import numpy as npdef RadixSort(a):  i = 0                       #初始為個位排序  n = 1                      #最小的位元置為1(包含0)  max = np.max(a)            #得到帶排序數組中最大數  while max/(10**n) > 0:       #得到最大數是幾位元    n += 1  while i < n:    bucket = {}               #用字典構建桶    for x in xrange(0,10):      bucket.setdefault(x, [])  #將每個桶置空    for x in a:                #對每一位進行排序      radix =(x / (10**i)) % 10  #得到每位的基數      bucket[radix].append(x) #將對應的數組元素加入到相應位基數的桶中    j = 0    for k in xrange(0, 10):      if len(bucket[k]) != 0:    #若桶不為空白        for y in bucket[k]:     #將該桶中每個元素          a[j] = y            #放回到數組中          j += 1    i += 1if __name__ == '__main__':  a = np.random.randint(0, 1000, size = 10)  print "Before sorting..."  print "---------------------------------------------------------------"  print a  print "---------------------------------------------------------------"  RadixSort(a)  print "After sorting..."  print "---------------------------------------------------------------"  print a  print "---------------------------------------------------------------"

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.