python插入排序_从Python看排序:插入排序
在學習排序算法時,我們可以經??吹讲迦肱判虻纳碛?。我們繼續用撲克牌來描述該算法的實現方式。假設有5張牌以如下方式堆放在桌面上:
將面上的一張牌拿起并放在手上:
因為這是第一張牌,所以我們無需考慮其位置。接著再從桌面上拿起面上的一張牌并與手上的牌進行比較,然后插入到正確的位置上:
接下來的操作與此相同。將梅花5取出然后放在梅花3和梅花8之間:
重復該過程直到所有的牌都從桌上拿起并插入到手中幾張牌中的正確位置。
整個過程中,插入排序同時維護兩組元素,一組排序后的元素和一組待排序的元素。在上面的撲克牌例子中,桌上的一疊撲克就是待排序的元素組,手上的牌則是排序后的元素組。在程序中處理該算法時,我們將在同一序列結構中處理這兩組元素。算法以列表左側作為排序后的元素位并始終從未排序組中取出第一位進行排序操作。要定位一個元素的正確位置,必須通過搜索來解決,然后移動右邊的各元素來為其讓位。下面用Python實現一個簡單的插入排序算法:
#Sorts a sequence in ascending order using the insertion sort algorithm.
def insertionSort( theSeq ):
n = len(theSeq)
# Starts with the first item as the only sorted entry.
for i in range( 1, n ):
# Save the value to be positioned.
value = theSeq[i]
# Find the position where value fits in the ordered part of the list.
pos = i
while pos > 0 and value < theSeq[pos - 1]:
# Shift the items to the right during the search.
theSeq[pos] = theSeq[pos - 1]
pos -= 1
# Put the saved value into the open slot.
theSeq[pos] = value
insertionSort()方法首先假設列表中的第一個元素已經在其正確的位置上。然后從第二位開始迭代并對每一個元素執行排序。由此,排序后的組始終處于列表的前部而待排序的組則處于尾部。循環中的i可以看作這兩組的分界點。在內循環中,程序對當前元素進行定位,同時移動列表中的元素以為其騰出位置來。下圖演示了一個列表排序的整個過程。
更多請參考:Rance D. Necaise - 《Data Structures and Algorithms Using Python》
總結
以上是生活随笔為你收集整理的python插入排序_从Python看排序:插入排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ssis 排程更新
- 下一篇: IT部门绩效考核:一本糊涂账?