主要参考:
八大排序算法的 Python 实现
http://python.jobbole.com/82270/
和
算法导论
以下摘自:伯乐在线:http://blog.jobbole.com/70639/
归并排序算法是目前为止我们拥有的最重要的算法之一。它是一种基于比较的排序算法,使用分治法解决那些原本复杂度为O(N^2)的问题。归并排序是由数学家John von Neumann于1945年发明的。
快速排序是解决排序问题的另一种途径,它使用就地分解算法,同时它也是一种分治算法。这个算法的问题在于它是不稳定的排序算法,但它在基于内存的数组排序上确实非常高效。
最后,堆排序算法使用一个优先队列降低数据的查找时间,它也是一种就地排序算法,同样也是不稳定的排序算法。
相较于曾经使用的其他排序算法(如冒泡排序),上述算法带来了显著的改进。事实上,多亏了它们,今天我们才有了数据挖掘、人工智能、链接分析,以及世界上大部分的计算机工具,也包括网络在内。
先来感受一下排序的可视化吧:
用舞蹈来诠释排序算法,欢乐多多!
冒泡排序: http://t.cn/hrf58M
希尔排序:http://t.cn/hrosvb
选择排序:http://t.cn/hros6e
插入排序:http://t.cn/hros0W
快速排序:http://t.cn/ScTA1d
归并排序:http://t.cn/Sc1cGZ
视觉直观感受 7 种常用的排序算法
http://blog.jobbole.com/11745/
可视化对比十多种排序算法(C#版)
http://blog.jobbole.com/72850/
接下来自己实践操作一番
每个算法 先来段舞蹈观赏一下,然后找来各路牛人最直白的解释,最后是Python代码
1. 插入排序:
http://t.cn/hros0W
http://www.cnblogs.com/kkun/archive/2011/11/23/2260265.html
http://blog.jobbole.com/72850/
它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
如上图例子,
(a)有序序列:4,未排序:3,1,2,从3开始,从后向前,先跟4比较大小,如果3<4,则交换二者位置
Insertion sort works the way many people sort a hand of playing cards.
We start with an empty left hand and the cards face down on the table.
We then remove one card at a time from the table and insert it into the correct position in the left hand.
To find the correct position for a card, we compare it with each of the cards already in the hand, from right to left,
def insert_sort(lists):
# 插入排序
count = len(lists)
for i in range(<span style="color:#ff0000;">1</span>, count):
key = lists[i]
j = i - 1
while j >= 0:
if lists[j] > key:
<span style="color:#ff0000;">lists[j + 1] = lists[j]
lists[j] = key</span>
j -= 1
return lists
class solution():
def insersort(self,array):
for i in range(1,len(array)):
while array[i-1]>array[i] and i>=1:
t=array[i-1]
array[i-1]=array[i]
array[i]=t
i-=1
return array
#array=[4,2,1,3]
array=[4,3,2,1,3]
r=solution().insersort(array)
print(r)<span style="white-space:pre"> </span>#[1, 2, 3, 3, 4]
2. 冒泡排序:
http://t.cn/hrf58M
http://www.cnblogs.com/kkun/archive/2011/11/23/2260280.html
http://blog.csdn.net/morewindows/article/details/6657829
上图:
每次比较相邻的两个元素,如果第一个比第二个大,就交换他们两个。
第一轮&