Python實現(xiàn)排序方法常見的四種
1.冒泡排序,相鄰位置比較大小,將比較大的(或小的)交換位置
def maopao(a): for i in range(0,len(a)): for j in range(0,len(a)-i-1): if a[j]>a[j+1]: temp = a[j+1] a[j+1] = a[j] a[j] = temp #print(a) #print(a) print(a)
2.選擇排序,遍歷選擇一個最小的數(shù)與當前循環(huán)的第一個數(shù)交換
def xuanze(a): for i in range(0,len(a)): k=i temp = a[i] for j in range(i,len(a)): if a[j]<temp: temp = a[j] k = j a[k] = a[i] a[i] = temp print(a)
3.快速排序:將子段的第一個元素做為中值,先從右向左遍歷,如過比中值大high-1,如果比中值小,將這個值放到low那里。
然后從左向右開始遍歷,如果左側的比中值大,將他放到high那里。當low>=high時,將中值的值賦給low
(1.以下為參照公眾號中的做法:
a =[7,1,3,2,6,54,4,4,5,8,12,34] def sort(a,low,high): while low < high: temp = a[low] while low < high and a[high]>=temp: high = high-1 a[low]=a[high] while low<high and a[low]<temp: low = low+1 a[high]=a[low] a[low]=temp return low def quicksort(a,low,high): if low<high: middle = sort(a,low,high) quicksort(a,low,middle) quicksort(a,middle+1,high) print(a) sort(a,0,len(a)-1) quicksort(a,0,len(a)-1) print(a)
(2.以下是參照網(wǎng)上的做法:
在做快速排序時一直各種問題,是因為地柜那里沒有考慮清楚,一直把low的值賦值為0了,實際上應該是不固定的low值,他每個子循環(huán)不定。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' a =[7,1,3,2,6,54,4,4,5,8,12,34] def sort(a,low,high): while low < high: temp = a[low] while low < high and a[high]>=temp: high = high-1 while low<high and a[high]<temp: a[low]=a[high] low =low+1 a[high]=a[low] a[low]=temp return low def quicksort(a,low,high): if low<high: middle = sort(a,low,high) quicksort(a,low,middle) quicksort(a,middle+1,high) print(a) sort(a,0,len(a)-1) quicksort(a,0,len(a)-1) print(a)
4.插入排序:從左向右遍歷,依次選取數(shù)值,從數(shù)值的左側從右向左遍歷,選擇第一個比他小的數(shù)值的右側插入該數(shù)值,其他數(shù)值依次向后賦值
#插入排序 a =[7,1,3,2,6,54,4,4,5,8,12,34] for i in range(0,len(a)-1): temp=a[i+1] j=i+1 while j>=0 and temp<a[j-1]: j=j-1 print(j) if j>=-1: k= i+1 while k>=j: a[k]=a[k-1] k=k-1 print(a) a[j]=temp print(a)
插入排序方法2,用到了列表的a.insert(1,2)和清楚a[2:3]=[],這樣可以少用一個循環(huán)
a =[7,1,3,2,6,54,4,4,5,8,12,34] for i in range(1,len(a)-1): temp=a[i] j=i-1 while j>=0 and temp<=a[j]: print(temp) j=j-1 if j >=-1: a[i:i+1]=[] a.insert(j+1,temp) print(a) print(a)
到此這篇關于Python實現(xiàn)排序的四種方法的文章就介紹到這了,更多相關python排序方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解Python GUI編程之PyQt5入門到實戰(zhàn)
這篇文章主要介紹了詳解Python GUI編程之PyQt5入門到實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12python 使用遞歸實現(xiàn)打印一個數(shù)字的每一位示例
今天小編就為大家分享一篇python 使用遞歸實現(xiàn)打印一個數(shù)字的每一位示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python中unittest的數(shù)據(jù)驅動詳解
這篇文章主要介紹了Python中unittest的數(shù)據(jù)驅動詳解,數(shù)據(jù)驅動測試,是一種單元測試框架,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08Django數(shù)據(jù)結果集序列化并展示實現(xiàn)過程
這篇文章主要介紹了Django數(shù)據(jù)結果集序列化并展示實現(xiàn)過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04