排序算法 之 插入排序InsertionSort

介紹

插入排序的工作原理是,對於每個未排序數據,在已排序序列中從後向前掃描,找到相應位置並插入。

步驟

  • 從第一個元素開始,該元素可以認爲已經被排序
  • 取出下一個元素,在已經排序的元素序列中從後向前掃描
  • 如果被掃描的元素(已排序)大於新元素,將該元素後移一位
  • 重複步驟3,直到找到已排序的元素小於或者等於新元素的位置
  • 將新元素插入到該位置後
  • 重複步驟2~5

這裏寫圖片描述

這裏寫圖片描述

代碼

# -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 10:41:00 2016

@author: zang
"""

from matplotlib import pyplot as plt
import random

def bubbleSort1(unsortedList):#採用遞歸
    if len(unsortedList)<2:
        return unsortedList

    list_length=len(unsortedList)
    for i in range(list_length - 1):
        if unsortedList[i] > unsortedList[i + 1]:
            unsortedList[i],unsortedList[i + 1] = unsortedList[i + 1], unsortedList[i]
    max_num = unsortedList.pop() 
    return bubbleSort1(unsortedList) + [max_num]  

def insertSort(unsortedList):
    n = len(unsortedList)
    for i in range(1,n):
        if unsortedList[i] < unsortedList[i-1]:
            temp = unsortedList[i]
            index = i           #待插入的下標
            for j in range(i-1,-1,-1):  #從i-1 循環到 0 (包括0)
                if unsortedList[j] > temp :
                    unsortedList[j+1] = unsortedList[j]
                    index = j   #記錄待插入下標
                else :
                    break
            unsortedList[index] = temp
    return unsortedList  

def plotScatter(inputList):
    plt.scatter(range(len(inputList)),inputList)
    plt.show()

if __name__ == "__main__":
    num_list = range(1000)
    unsortedList = random.sample(num_list, 30)
    print "unsortedList:"
    plotScatter(unsortedList)
    print unsortedList
    sortedList = insertSort(unsortedList)
    print "sortedList:"
    plotScatter(sortedList)
    print sortedList

測試

輸入

[544, 757, 514, 875, 371, 44, 538, 296, 155, 148, 612, 847, 352, 973, 654, 135, 956, 197, 655, 270, 280, 609, 175, 891, 450, 128, 75, 260, 248, 540]

這裏寫圖片描述
輸出

[44, 75, 128, 135, 148, 155, 175, 197, 248, 260, 270, 280, 296, 352, 371, 450, 514, 538, 540, 544, 609, 612, 654, 655, 757, 847, 875, 891, 956, 973]

這裏寫圖片描述

分析

情況 性能
Worst case performance: O(n2)
Best case performance: O(n)
Average case performance: O(n2)
Worst case space complexity: O(1)

參考

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