排序算法 之 插入排序InsertionSort

来源:互联网 发布:windows 2008 r2 编辑:程序博客网 时间:2024/04/30 05:31

介绍

插入排序的工作原理是,对于每个未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

步骤

  • 从第一个元素开始,该元素可以认为已经被排序
  • 取出下一个元素,在已经排序的元素序列中从后向前扫描
  • 如果被扫描的元素(已排序)大于新元素,将该元素后移一位
  • 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
  • 将新元素插入到该位置后
  • 重复步骤2~5

这里写图片描述

这里写图片描述

代码

# -*- coding: utf-8 -*-"""Created on Wed Apr 27 10:41:00 2016@author: zang"""from matplotlib import pyplot as pltimport randomdef 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)

参考

  • http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/
  • http://blog.jobbole.com/72850/
0 0
原创粉丝点击