排序算法 之 插入排序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]
分析
参考
- http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/
- http://blog.jobbole.com/72850/
0 0
- 排序算法 之 插入排序InsertionSort
- 插入排序(InsertionSort)
- 插入排序 - InsertionSort
- 插入排序insertionSort
- insertionSort()插入排序
- 插入排序(InsertionSort)
- 插入排序InsertionSort
- 插入排序(1)InsertionSort
- InsertionSort -- 插入排序(C++)
- [MIPS汇编语言]InsertionSort插入排序
- 插入排序InsertionSort(C++实现)
- 插入排序InsertionSort(Python实现)
- 【算法导论学习-001】插入排序(InsertionSort)
- 排序——插入排序(insertionsort)
- 1、直接插入排序(InsertionSort)-C#实现
- [硕.Love Python] InsertionSort(插入排序)
- 排序算法之插入排序
- 排序算法之插入排序
- 关于 1<<0 的意义
- 关于rand和srand函数使用的一点心得
- C++ 算法笔试十题
- SPFA 模板
- Android实现退出整个应用程序代码;
- 排序算法 之 插入排序InsertionSort
- Ubuntu下slickedit的安装与配置
- 改HTML5里的input标签的required属性的提示为英文的
- POJ 1740 A New Stone Game【博弈】
- java之生产者消费者模式
- 4-5 报数 (20分)
- 欢迎使用CSDN-markdown编辑器
- Swift-常量与变量
- tjut 1159