The Insertion Sort

插入排序法

  1. 默認第一個元素爲最小,默認他是排序的
  2. 從第二個元素查找, 如果,第二個元素比第一個小,那麼對調位置。
  3. 以此類推
mark first element as sorted
for each unsorted element
  'extract' the element
  for i = lastSortedIndex to 0
    if currentSortedElement > extractedElement
      #如果被取出的元素小於前面排好的元素
      move sorted element to the right by 1
      #那麼前面排好的元素向後挪
    else: insert extracted element
def insertionSort(alist):

   for index in range(1,len(alist)):
     #他從第二位開始循環的
     #循環list 得到每個元素的值
     currentvalue = alist[index]
     #他們的INDEX 爲位置
     position = index

     #當有位置,並且鏈表中前一個元素大於目前這個元素
     while position>0 and alist[position-1]>currentvalue:
         #一個一個向前比較
         #對調
         alist[position]=alist[position-1]
         position = position-1

     alist[position]=currentvalue

alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)

內部比較,然後換位

這裏寫圖片描述

發佈了5 篇原創文章 · 獲贊 3 · 訪問量 9529
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章