diff --git a/4.shellSort.md b/4.shellSort.md index 0406030..925e24f 100644 --- a/4.shellSort.md +++ b/4.shellSort.md @@ -9,6 +9,10 @@ 希尔排序的基本思想是:先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录“基本有序”时,再对全体记录进行依次直接插入排序。 +下面给出博客[八大排序算法-shell 排序](http://blog.csdn.net/qishouzhang/article/details/47065381) 中的一张图 + + +![](http://p1r3973u8.bkt.clouddn.com/image/jpg/sort-shell.jpg20150726092554557) ## 1. 算法步骤 @@ -63,6 +67,30 @@ def shellSort(arr): } ``` +不太明白作者一下代码的含义, +```python +while(gap < len(arr)/3): + gap = gap*3+1 +``` +按照大部分博客说每次都除以2,以下代码也是可行的 +```python +def shellSort(arr): + import math + gap=len(arr)/2 + + while gap > 0: + for i in range(gap,len(arr)): + temp = arr[i] + j = i-gap + while j >=0 and arr[j] > temp: + arr[j+gap]=arr[j] + j-=gap + arr[j+gap] = temp + gap = gap/2 + return arr + +``` + ## 4. Go 代码实现 ```go diff --git a/5.mergeSort.md b/5.mergeSort.md index e1e1479..76a86c8 100644 --- a/5.mergeSort.md +++ b/5.mergeSort.md @@ -76,10 +76,9 @@ function merge(left, right) ```python def mergeSort(arr): - import math if(len(arr)<2): return arr - middle = math.floor(len(arr)/2) + middle = len(arr)/2 left, right = arr[0:middle], arr[middle:] return merge(mergeSort(left), mergeSort(right)) @@ -87,13 +86,13 @@ def merge(left,right): result = [] while left and right: if left[0] <= right[0]: - result.append(left.pop(0)); + result.append(left.pop(0)) else: - result.append(right.pop(0)); - while left: - result.append(left.pop(0)); - while right: - result.append(right.pop(0)); + result.append(right.pop(0)) + if left: + result.extend(left) + if right: + result.extend(right) return result ``` diff --git a/6.quickSort.md b/6.quickSort.md index d08b28f..c7c1973 100644 --- a/6.quickSort.md +++ b/6.quickSort.md @@ -21,7 +21,19 @@ 递归的最底部情形,是数列的大小是零或一,也就是永远都已经被排序好了。虽然一直递归下去,但是这个算法总会退出,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。 - +下面给出一个示例: +``` +假设有数据6 1 2 7 9 3 4 5 10 8 +首先用6当作基准,使用i j两个指针分别从两边进行扫描,把比6小的元素和比6大的元素分开。 +取出6那么就留个坑变成:_ 1 2 7 9 3 4 5 10 8 +从右边(j)开始,一步步向左移,找到比6小的数;这个数为5,将5放置到坑中,留下新的坑:5 1 2 7 9 3 4 _(j) 10 8 +然后从左边(i)一步步向右移,找到比6大的数,这个数为7,将7放置到坑中,留下新的坑:5 1 2 _(i) 9 3 4 7(j) 10 8。其实这两步就是将5和7互换。 +然后j继续右移找到比6小的数4,i左移动找到比6大的数9,然后互换,依次变成:5 1 2 4(i) 9 3 _(j) 7 10 8 和 5 1 2 4 _(i) 3 9(j) 7 10 8 +然后j继续右移,发现3<6,然后3填坑,留下新的坑:5 1 2 4 3(i) _(j) 9 7 10 8 +然后i继续左移,发现i=j,此时把基准6填在碰头的位置5 1 2 4 3 6(i)(j) 9 7 10 8 +此时我们已经将原来的序列,以 6 为分界点拆分成了两个序列,左边的序列是“5 1 2 4 3”,右边的序列是“ 9 7 10 8 ”然后递归左边和右边。 +``` +可参考:[算法 3:最常用的排序——快速排序](http://wiki.jikexueyuan.com/project/easy-learn-algorithm/fast-sort.html) ## 2. 动图演示 ![动图演示](res/quickSort.gif) diff --git a/7.heapSort.md b/7.heapSort.md index d4bfa49..de92ac9 100644 --- a/7.heapSort.md +++ b/7.heapSort.md @@ -18,6 +18,7 @@ 4. 重复步骤 2,直到堆的尺寸为 1。 +过程示例可参考:[图解排序算法(三)之堆排序](https://www.cnblogs.com/chengxiao/p/6129630.html) ## 2. 动图演示