From 234e919679466676b314f170ab2cb32a04969b2f Mon Sep 17 00:00:00 2001 From: wilon Date: Mon, 26 Jun 2017 16:46:28 +0800 Subject: [PATCH 1/3] php sort --- 1.bubbleSort.md => 01.bubbleSort.md | 56 ++---- 02.selectionSort.md | 39 ++++ 03.insertionSort.md | 37 ++++ 04.shellSort.md | 43 ++++ 05.mergeSort.md | 74 +++++++ 06.quickSort.md | 54 +++++ 07.heapSort.md | 77 +++++++ 08.countingSort.md | 39 ++++ 09.bucketSort.md | 62 ++++++ 10.radixSort.md | 50 +++-- 2.selectionSort.md | 68 ------- 3.insertionSort.md | 67 ------- 4.shellSort.md | 89 --------- 5.mergeSort.md | 138 ------------- 6.quickSort.md | 185 ----------------- 7.heapSort.md | 149 -------------- 8.countingSort.md | 82 -------- 9.bucketSort.md | 64 ------ README.md | 35 ++-- src/phpSortTest.php | 299 ++++++++++++++++++++++++++++ test/pythonSortTest.py | 165 --------------- 21 files changed, 782 insertions(+), 1090 deletions(-) rename 1.bubbleSort.md => 01.bubbleSort.md (65%) create mode 100644 02.selectionSort.md create mode 100644 03.insertionSort.md create mode 100644 04.shellSort.md create mode 100644 05.mergeSort.md create mode 100644 06.quickSort.md create mode 100644 07.heapSort.md create mode 100644 08.countingSort.md create mode 100644 09.bucketSort.md delete mode 100644 2.selectionSort.md delete mode 100644 3.insertionSort.md delete mode 100644 4.shellSort.md delete mode 100644 5.mergeSort.md delete mode 100644 6.quickSort.md delete mode 100644 7.heapSort.md delete mode 100644 8.countingSort.md delete mode 100644 9.bucketSort.md create mode 100644 src/phpSortTest.php delete mode 100644 test/pythonSortTest.py diff --git a/1.bubbleSort.md b/01.bubbleSort.md similarity index 65% rename from 1.bubbleSort.md rename to 01.bubbleSort.md index e53a38d..397aff1 100644 --- a/1.bubbleSort.md +++ b/01.bubbleSort.md @@ -31,49 +31,21 @@ 当输入的数据是反序时(写一个 for 循环反序输出数据不就行了,干嘛要用你冒泡排序呢,我是闲的吗)。 -## 5. JavaScript 代码实现 - -```js -function bubbleSort(arr) { - var len = arr.length; - for (var i = 0; i < len - 1; i++) { - for (var j = 0; j < len - 1 - i; j++) { - if (arr[j] > arr[j+1]) { // 相邻元素两两对比 - var temp = arr[j+1]; // 元素交换 - arr[j+1] = arr[j]; - arr[j] = temp; +## 5. PHP 代码实现 + +```php +function bubbleSort($arr) +{ + $len = count($arr); + for ($i = 0; $i < $len - 1; $i++) { + for ($j = 0; $j < $len - 1 - $i; $j++) { + if ($arr[$j] > $arr[$j+1]) { + $tmp = $arr[$j]; + $arr[$j] = $arr[$j+1]; + $arr[$j+1] = $tmp; } } } - return arr; + return $arr; } -``` - - - -## 6. Python 代码实现 - -```python -def bubbleSort(arr): - for i in range(1, len(arr)): - for j in range(0, len(arr)-i): - if arr[j] > arr[j+1]: - arr[j], arr[j + 1] = arr[j + 1], arr[j] - return arr -``` - -## 7. Go 代码实现 - -```go -func bubbleSort(arr []int) []int { - length := len(arr) - for i := 0; i < length; i++ { - for j := 0; j < length-1-i; j++ { - if arr[j] > arr[j+1] { - arr[j], arr[j+1] = arr[j+1], arr[j] - } - } - } - return arr -} -``` +``` \ No newline at end of file diff --git a/02.selectionSort.md b/02.selectionSort.md new file mode 100644 index 0000000..dc5f1f2 --- /dev/null +++ b/02.selectionSort.md @@ -0,0 +1,39 @@ +# 选择排序 + +选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n²) 的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。 + + +## 1. 算法步骤 + +1. 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置 + +2. 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。 + +3. 重复第二步,直到所有元素均排序完毕。 + + +## 2. 动图演示 + +![动图演示](res/selectionSort.gif) + + +## 3. PHP 代码实现 + +```php +function selectionSort($arr) +{ + $len = count($arr); + for ($i = 0; $i < $len - 1; $i++) { + $minIndex = $i; + for ($j = $i + 1; $j < $len; $j++) { + if ($arr[$j] < $arr[$minIndex]) { + $minIndex = $j; + } + } + $temp = $arr[$i]; + $arr[$i] = $arr[$minIndex]; + $arr[$minIndex] = $temp; + } + return $arr; +} +``` diff --git a/03.insertionSort.md b/03.insertionSort.md new file mode 100644 index 0000000..e184097 --- /dev/null +++ b/03.insertionSort.md @@ -0,0 +1,37 @@ +# 插入排序 + +插入排序的代码实现虽然没有冒泡排序和选择排序那么简单粗暴,但它的原理应该是最容易理解的了,因为只要打过扑克牌的人都应该能够秒懂。插入排序是一种最简单直观的排序算法,它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 + +插入排序和冒泡排序一样,也有一种优化算法,叫做拆半插入。 + + +## 1. 算法步骤 + +1. 将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。 + +2. 从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。) + + +## 2. 动图演示 + +![动图演示](res/insertionSort.gif) + + +## 3. PHP 代码实现 + +```php +function insertionSort($arr) { + $len = count($arr); + for ($i = 1; $i < $len; $i++) { + $preIndex = $i - 1; + $current = $arr[$i]; + while($preIndex >= 0 && $arr[$preIndex] > $current) { + $arr[$preIndex+1] = $arr[$preIndex]; + $preIndex--; + } + $arr[$preIndex+1] = $current; + } + return $arr; +} +``` + diff --git a/04.shellSort.md b/04.shellSort.md new file mode 100644 index 0000000..0f77c12 --- /dev/null +++ b/04.shellSort.md @@ -0,0 +1,43 @@ +# 希尔排序 + +希尔排序,也称递减增量排序算法,是插入排序的一种更高效的改进版本。但希尔排序是非稳定排序算法。 + +希尔排序是基于插入排序的以下两点性质而提出改进方法的: + + - 插入排序在对几乎已经排好序的数据操作时,效率高,即可以达到线性排序的效率; + - 但插入排序一般来说是低效的,因为插入排序每次只能将数据移动一位; + +希尔排序的基本思想是:先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录“基本有序”时,再对全体记录进行依次直接插入排序。 + + +## 1. 算法步骤 + +1. 选择一个增量序列 t1,t2,……,tk,其中 ti > tj, tk = 1; + +2. 按增量序列个数 k,对序列进行 k 趟排序; + +3. 每趟排序,根据对应的增量 ti,将待排序列分割成若干长度为 m 的子序列,分别对各子表进行直接插入排序。仅增量因子为 1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 + + +## 2. PHP 代码实现 + +```php +function shellSort($arr) { + $len = count($arr); + $temp = 0; + $gap = 1; + while($gap < $len / 3) { + $gap = $gap * 3 + 1; + } + for ($gap; $gap > 0; $gap = floor($gap / 3)) { + for ($i = $gap; $i < $len; $i++) { + $temp = $arr[$i]; + for ($j = $i - $gap; $j >= 0 && $arr[$j] > $temp; $j -= $gap) { + $arr[$j+$gap] = $arr[$j]; + } + $arr[$j+$gap] = $temp; + } + } + return $arr; +} +``` diff --git a/05.mergeSort.md b/05.mergeSort.md new file mode 100644 index 0000000..edeb58f --- /dev/null +++ b/05.mergeSort.md @@ -0,0 +1,74 @@ +# 归并排序 + +归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。 + +作为一种典型的分而治之思想的算法应用,归并排序的实现由两种方法: + - 自上而下的递归(所有递归的方法都可以用迭代重写,所以就有了第 2 种方法); + - 自下而上的迭代; + +在《数据结构与算法 JavaScript 描述》中,作者给出了自下而上的迭代方法。但是对于递归法,作者却认为: + +> However, it is not possible to do so in JavaScript, as the recursion goes too deep for the language to handle. +> +> 然而,在 JavaScript 中这种方式不太可行,因为这个算法的递归深度对它来讲太深了。 + + +说实话,我不太理解这句话。意思是 JavaScript 编译器内存太小,递归太深容易造成内存溢出吗?还望有大神能够指教。 + +和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是 O(nlogn) 的时间复杂度。代价是需要额外的内存空间。 + + +## 2. 算法步骤 + +1. 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列; + +2. 设定两个指针,最初位置分别为两个已经排序序列的起始位置; + +3. 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置; + +4. 重复步骤 3 直到某一指针达到序列尾; + +5. 将另一序列剩下的所有元素直接复制到合并序列尾。 + + +## 3. 动图演示 + +![动图演示](res/mergeSort.gif) + + +## 4. PHP 代码实现 + +```php +function mergeSort($arr) { + $len = count($arr); + if ($len < 2) { + return $arr; + } + $middle = floor($len / 2); + $left = array_slice($arr, 0, $middle); + $right = array_slice($arr, $middle); + return merge(mergeSort($left), mergeSort($right)); +} + +function merge($left, $right) +{ + $result = []; + + while (count($left) > 0 && count($right) > 0) { + if ($left[0] <= $right[0]) { + $result[] = array_shift($left); + } else { + $result[] = array_shift($right); + } + } + + while (count($left)) + $result[] = array_shift($left); + + while (count($right)) + $result[] = array_shift($right); + + return $result; +} + +``` diff --git a/06.quickSort.md b/06.quickSort.md new file mode 100644 index 0000000..277f597 --- /dev/null +++ b/06.quickSort.md @@ -0,0 +1,54 @@ +# 快速排序 + +快速排序是由东尼·霍尔所发展的一种排序算法。在平均状况下,排序 n 个项目要 Ο(nlogn) 次比较。在最坏状况下则需要 Ο(n2) 次比较,但这种状况并不常见。事实上,快速排序通常明显比其他 Ο(nlogn) 算法更快,因为它的内部循环(inner loop)可以在大部分的架构上很有效率地被实现出来。 + +快速排序使用分治法(Divide and conquer)策略来把一个串行(list)分为两个子串行(sub-lists)。 + +快速排序又是一种分而治之思想在排序算法上的典型应用。本质上来看,快速排序应该算是在冒泡排序基础上的递归分治法。 + +快速排序的名字起的是简单粗暴,因为一听到这个名字你就知道它存在的意义,就是快,而且效率高!它是处理大数据最快的排序算法之一了。虽然 Worst Case 的时间复杂度达到了 O(n²),但是人家就是优秀,在大多数情况下都比平均时间复杂度为 O(n logn) 的排序算法表现要更好,可是这是为什么呢,我也不知道。好在我的强迫症又犯了,查了 N 多资料终于在《算法艺术与信息学竞赛》上找到了满意的答案: + +> 快速排序的最坏运行情况是 O(n²),比如说顺序数列的快排。但它的平摊期望时间是 O(nlogn),且 O(nlogn) 记号中隐含的常数因子很小,比复杂度稳定等于 O(nlogn) 的归并排序要小很多。所以,对绝大多数顺序性较弱的随机数列而言,快速排序总是优于归并排序。 + + +## 1. 算法步骤 + +1. 从数列中挑出一个元素,称为 “基准”(pivot); + +2. 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作; + +3. 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序; + +递归的最底部情形,是数列的大小是零或一,也就是永远都已经被排序好了。虽然一直递归下去,但是这个算法总会退出,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。 + + +## 2. 动图演示 + +![动图演示](res/quickSort.gif) + + +## 3. PHP 代码实现 + +```php +function quickSort($arr) +{ + if (count($arr) <= 1) + return $arr; + $middle = $arr[0]; + $leftArray = array(); + $rightArray = array(); + + for ($i = 1; $i < count($arr); $i++) { + if ($arr[$i] > $middle) + $rightArray[] = $arr[$i]; + else + $leftArray[] = $arr[$i]; + } + $leftArray = quickSort($leftArray); + $leftArray[] = $middle; + + $rightArray = quickSort($rightArray); + return array_merge($leftArray, $rightArray); +} +``` + diff --git a/07.heapSort.md b/07.heapSort.md new file mode 100644 index 0000000..18362fb --- /dev/null +++ b/07.heapSort.md @@ -0,0 +1,77 @@ +# 堆排序 + +堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。堆排序可以说是一种利用堆的概念来排序的选择排序。分为两种方法: + +1. 大顶堆:每个节点的值都大于或等于其子节点的值,在堆排序算法中用于升序排列; +2. 小顶堆:每个节点的值都小于或等于其子节点的值,在堆排序算法中用于降序排列; + +堆排序的平均时间复杂度为 Ο(nlogn)。 + + +## 1. 算法步骤 + +1. 创建一个堆 H[0……n-1]; + +2. 把堆首(最大值)和堆尾互换; + +3. 把堆的尺寸缩小 1,并调用 shift_down(0),目的是把新的数组顶端数据调整到相应位置; + +4. 重复步骤 2,直到堆的尺寸为 1。 + + +## 2. 动图演示 + +![动图演示](res/heapSort.gif) + + +## 3. PHP 代码实现 + +```php +function buildMaxHeap(&$arr) +{ + global $len; + for ($i = floor($len/2); $i >= 0; $i--) { + heapify($arr, $i); + } +} + +function heapify(&$arr, $i) +{ + global $len; + $left = 2 * $i + 1; + $right = 2 * $i + 2; + $largest = $i; + + if ($left < $len && $arr[$left] > $arr[$largest]) { + $largest = $left; + } + + if ($right < $len && $arr[$right] > $arr[$largest]) { + $largest = $right; + } + + if ($largest != $i) { + swap($arr, $i, $largest); + heapify($arr, $largest); + } +} + +function swap(&$arr, $i, $j) +{ + $temp = $arr[$i]; + $arr[$i] = $arr[$j]; + $arr[$j] = $temp; +} + +function heapSort($arr) { + global $len; + $len = count($arr); + buildMaxHeap($arr); + for ($i = count($arr) - 1; $i > 0; $i--) { + swap($arr, 0, $i); + $len--; + heapify($arr, 0); + } + return $arr; +} +``` diff --git a/08.countingSort.md b/08.countingSort.md new file mode 100644 index 0000000..d3b6557 --- /dev/null +++ b/08.countingSort.md @@ -0,0 +1,39 @@ +# 计数排序 + +计数排序的核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。 + +## 1. 动图演示 + +![动图演示](res/countingSort.gif) + + +## 2. PHP 代码实现 + +```php + +function countingSort($arr, $maxValue = null) +{ + if ($maxValue === null) { + $maxValue = max($arr); + } + for ($m = 0; $m < $maxValue + 1; $m++) { + $bucket[] = null; + } + + $arrLen = count($arr); + for ($i = 0; $i < $arrLen; $i++) { + if (!array_key_exists($arr[$i], $bucket)) { + $bucket[$arr[$i]] = 0; + } + $bucket[$arr[$i]]++; + } + + $sortedIndex = 0; + foreach ($bucket as $key => $len) { + if ($len !== null) $arr[$sortedIndex++] = $key; + } + + return $arr; +} +``` + diff --git a/09.bucketSort.md b/09.bucketSort.md new file mode 100644 index 0000000..1369110 --- /dev/null +++ b/09.bucketSort.md @@ -0,0 +1,62 @@ +# 桶排序 + +桶排序是计数排序的升级版。它利用了函数的映射关系,高效与否的关键就在于这个映射函数的确定。为了使桶排序更加高效,我们需要做到这两点: + +1. 在额外空间充足的情况下,尽量增大桶的数量 +2. 使用的映射函数能够将输入的 N 个数据均匀的分配到 K 个桶中 + +同时,对于桶中元素的排序,选择何种比较排序算法对于性能的影响至关重要。 + + +## 1. 什么时候最快 + +当输入的数据可以均匀的分配到每一个桶中。 + + +## 2. 什么时候最慢 + +当输入的数据被分配到了同一个桶中。 + + +## 3. PHP 代码实现 + +```php + +function bucketSort($arr, $bucketSize = 5) +{ + if (count($arr) === 0) { + return $arr; + } + + $minValue = $arr[0]; + $maxValue = $arr[0]; + for ($i = 1; $i < count($arr); $i++) { + if ($arr[$i] < $minValue) { + $minValue = $arr[$i]; + } else if ($arr[$i] > $maxValue) { + $maxValue = $arr[$i]; + } + } + + $bucketCount = floor(($maxValue - $minValue) / $bucketSize) + 1; + $buckets = array(); + for ($i = 0; $i < count($buckets); $i++) { + $buckets[$i] = []; + } + + for ($i = 0; $i < count($arr); $i++) { + $buckets[floor(($arr[$i] - $minValue) / $bucketSize)][] = $arr[$i]; + } + + $arr = array(); + for ($i = 0; $i < count($buckets); $i++) { + $bucketTmp = $buckets[$i]; + sort($bucketTmp); + for ($j = 0; $j < count($bucketTmp); $j++) { + $arr[] = $bucketTmp[$j]; + } + } + + return $arr; +} +``` \ No newline at end of file diff --git a/10.radixSort.md b/10.radixSort.md index 5f40ea7..3277bf4 100644 --- a/10.radixSort.md +++ b/10.radixSort.md @@ -19,32 +19,40 @@ ![动图演示](res/radixSort.gif) -## 3. JavaScript 代码实现 - -```js -//LSD Radix Sort -var counter = []; -function radixSort(arr, maxDigit) { - var mod = 10; - var dev = 1; - for (var i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) { - for(var j = 0; j < arr.length; j++) { - var bucket = parseInt((arr[j] % mod) / dev); - if(counter[bucket]==null) { - counter[bucket] = []; +## 3. PHP 代码实现 + +```php + +function radixSort($arr, $maxDigit = null) +{ + if ($maxDigit === null) { + $maxDigit = max($arr); + } + $counter = []; + for ($i = 0; $i < $maxDigit; $i++) { + for ($j = 0; $j < count($arr); $j++) { + preg_match_all('/\d/', (string) $arr[$j], $matches); + $numArr = $matches[0]; + $lenTmp = count($numArr); + $bucket = array_key_exists($lenTmp - $i - 1, $numArr) + ? intval($numArr[$lenTmp - $i - 1]) + : 0; + if (!array_key_exists($bucket, $counter)) { + $counter[$bucket] = []; } - counter[bucket].push(arr[j]); + $counter[$bucket][] = $arr[$j]; } - var pos = 0; - for(var j = 0; j < counter.length; j++) { - var value = null; - if(counter[j]!=null) { - while ((value = counter[j].shift()) != null) { - arr[pos++] = value; + $pos = 0; + for ($j = 0; $j < count($counter); $j++) { + $value = null; + if ($counter[$j] !== null) { + while (($value = array_shift($counter[$j])) !== null) { + $arr[$pos++] = $value; } } } } - return arr; + + return $arr; } ``` \ No newline at end of file diff --git a/2.selectionSort.md b/2.selectionSort.md deleted file mode 100644 index 1c3ddbc..0000000 --- a/2.selectionSort.md +++ /dev/null @@ -1,68 +0,0 @@ -# 选择排序 - -选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n²) 的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。 - - -## 1. 算法步骤 - -1. 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置 - -2. 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。 - -3. 重复第二步,直到所有元素均排序完毕。 - - -## 2. 动图演示 - -![动图演示](res/selectionSort.gif) - - -## 3. JavaScript 代码实现 - -```js -function selectionSort(arr) { - var len = arr.length; - var minIndex, temp; - for (var i = 0; i < len - 1; i++) { - minIndex = i; - for (var j = i + 1; j < len; j++) { - if (arr[j] < arr[minIndex]) { // 寻找最小的数 - minIndex = j; // 将最小数的索引保存 - } - } - temp = arr[i]; - arr[i] = arr[minIndex]; - arr[minIndex] = temp; - } - return arr; -} -``` - -## 4. Python 代码实现 - -```python -def selectionSort(arr): - for i in range(len(arr)-1): - for j in range(i+1, len(arr)): - if arr[j] < arr[i]: - arr[i], arr[j] = arr[j], arr[i] - return arr -``` - -## 5. Go 代码实现 - -```go -func selectionSort(arr []int) []int { - length := len(arr) - for i := 0; i < length-1; i++ { - min := i - for j := i + 1; j < length; j++ { - if arr[min] > arr[j] { - min = j - } - } - arr[i], arr[min] = arr[min], arr[i] - } - return arr -} -``` diff --git a/3.insertionSort.md b/3.insertionSort.md deleted file mode 100644 index 11ed672..0000000 --- a/3.insertionSort.md +++ /dev/null @@ -1,67 +0,0 @@ -# 插入排序 - -插入排序的代码实现虽然没有冒泡排序和选择排序那么简单粗暴,但它的原理应该是最容易理解的了,因为只要打过扑克牌的人都应该能够秒懂。插入排序是一种最简单直观的排序算法,它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 - -插入排序和冒泡排序一样,也有一种优化算法,叫做拆半插入。 - - -## 1. 算法步骤 - -1. 将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。 - -2. 从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。) - - -## 2. 动图演示 - -![动图演示](res/insertionSort.gif) - - -## 3. JavaScript 代码实现 - -```js -function insertionSort(arr) { - var len = arr.length; - var preIndex, current; - for (var i = 1; i < len; i++) { - preIndex = i - 1; - current = arr[i]; - while(preIndex >= 0 && arr[preIndex] > current) { - arr[preIndex+1] = arr[preIndex]; - preIndex--; - } - arr[preIndex+1] = current; - } - return arr; -} -``` - -## 4. Python 代码实现 - -```python -def insertionSort(arr): - for i in range(len(arr)): - preIndex = i-1 - current = arr[i] - while preIndex >= 0 and arr[preIndex] > current: - arr[preIndex+1] = arr[preIndex] - preIndex-=1 - arr[preIndex+1] = current -    return arr -``` - -## 5. Go 代码实现 -```go -func insertionSort(arr []int) []int { - for i := range arr { - preIndex := i - 1 - current := arr[i] - for preIndex >= 0 && arr[preIndex] > current { - arr[preIndex+1] = arr[preIndex] - preIndex -= 1 - } - arr[preIndex+1] = current - } - return arr -} -``` diff --git a/4.shellSort.md b/4.shellSort.md deleted file mode 100644 index 0406030..0000000 --- a/4.shellSort.md +++ /dev/null @@ -1,89 +0,0 @@ -# 希尔排序 - -希尔排序,也称递减增量排序算法,是插入排序的一种更高效的改进版本。但希尔排序是非稳定排序算法。 - -希尔排序是基于插入排序的以下两点性质而提出改进方法的: - - - 插入排序在对几乎已经排好序的数据操作时,效率高,即可以达到线性排序的效率; - - 但插入排序一般来说是低效的,因为插入排序每次只能将数据移动一位; - -希尔排序的基本思想是:先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录“基本有序”时,再对全体记录进行依次直接插入排序。 - - -## 1. 算法步骤 - -1. 选择一个增量序列 t1,t2,……,tk,其中 ti > tj, tk = 1; - -2. 按增量序列个数 k,对序列进行 k 趟排序; - -3. 每趟排序,根据对应的增量 ti,将待排序列分割成若干长度为 m 的子序列,分别对各子表进行直接插入排序。仅增量因子为 1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 - - -## 2. JavaScript 代码实现 - -```js -function shellSort(arr) { - var len = arr.length, - temp, - gap = 1; - while(gap < len/3) { //动态定义间隔序列 - gap =gap*3+1; - } - for (gap; gap > 0; gap = Math.floor(gap/3)) { - for (var i = gap; i < len; i++) { - temp = arr[i]; - for (var j = i-gap; j >= 0 && arr[j] > temp; j-=gap) { - arr[j+gap] = arr[j]; - } - arr[j+gap] = temp; - } - } - return arr; -} -``` - -## 3. Python 代码实现 - -```python -def shellSort(arr): - import math - gap=1 - while(gap < len(arr)/3): - gap = gap*3+1 - 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 = math.floor(gap/3) - return arr -} -``` - -## 4. Go 代码实现 - -```go -func shellSort(arr []int) []int { - length := len(arr) - gap := 1 - for gap < gap/3 { - gap = gap*3 + 1 - } - for gap > 0 { - for i := gap; i < length; i++ { - temp := arr[i] - j := i - gap - for j >= 0 && arr[j] > temp { - arr[j+gap] = arr[j] - j -= gap - } - arr[j+gap] = temp - } - gap = gap / 3 - } - return arr -} -``` diff --git a/5.mergeSort.md b/5.mergeSort.md deleted file mode 100644 index e1e1479..0000000 --- a/5.mergeSort.md +++ /dev/null @@ -1,138 +0,0 @@ -# 归并排序 - -归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。 - -作为一种典型的分而治之思想的算法应用,归并排序的实现由两种方法: - - 自上而下的递归(所有递归的方法都可以用迭代重写,所以就有了第 2 种方法); - - 自下而上的迭代; - -在《数据结构与算法 JavaScript 描述》中,作者给出了自下而上的迭代方法。但是对于递归法,作者却认为: - -> However, it is not possible to do so in JavaScript, as the recursion goes too deep for the language to handle. -> -> 然而,在 JavaScript 中这种方式不太可行,因为这个算法的递归深度对它来讲太深了。 - - -说实话,我不太理解这句话。意思是 JavaScript 编译器内存太小,递归太深容易造成内存溢出吗?还望有大神能够指教。 - -和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是 O(nlogn) 的时间复杂度。代价是需要额外的内存空间。 - - -## 2. 算法步骤 - -1. 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列; - -2. 设定两个指针,最初位置分别为两个已经排序序列的起始位置; - -3. 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置; - -4. 重复步骤 3 直到某一指针达到序列尾; - -5. 将另一序列剩下的所有元素直接复制到合并序列尾。 - - -## 3. 动图演示 - -![动图演示](res/mergeSort.gif) - - -## 4. JavaScript 代码实现 - -```js -function mergeSort(arr) { // 采用自上而下的递归方法 - var len = arr.length; - if(len < 2) { - return arr; - } - var middle = Math.floor(len / 2), - left = arr.slice(0, middle), - right = arr.slice(middle); - return merge(mergeSort(left), mergeSort(right)); -} - -function merge(left, right) -{ - var result = []; - - while (left.length && right.length) { - if (left[0] <= right[0]) { - result.push(left.shift()); - } else { - result.push(right.shift()); - } - } - - while (left.length) - result.push(left.shift()); - - while (right.length) - result.push(right.shift()); - - return result; -} -``` - -## 5. Python 代码实现 - -```python -def mergeSort(arr): - import math - if(len(arr)<2): - return arr - middle = math.floor(len(arr)/2) - left, right = arr[0:middle], arr[middle:] - return merge(mergeSort(left), mergeSort(right)) - -def merge(left,right): - result = [] - while left and right: - if left[0] <= right[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)); - return result -``` - -## 6. Go 代码实现 - -```go -func mergeSort(arr []int) []int { - length := len(arr) - if length < 2 { - return arr - } - middle := length / 2 - left := arr[0:middle] - right := arr[middle:] - return merge(mergeSort(left), mergeSort(right)) -} - -func merge(left []int, right []int) []int { - var result []int - for len(left) != 0 && len(right) != 0 { - if left[0] <= right[0] { - result = append(result, left[0]) - left = left[1:] - } else { - result = append(result, right[0]) - right = right[1:] - } - } - - for len(left) != 0 { - result = append(result, left[0]) - left = left[1:] - } - - for len(right) != 0 { - result = append(result, right[0]) - right = right[1:] - } - - return result -} -``` diff --git a/6.quickSort.md b/6.quickSort.md deleted file mode 100644 index 1c81c59..0000000 --- a/6.quickSort.md +++ /dev/null @@ -1,185 +0,0 @@ -# 快速排序 - -快速排序是由东尼·霍尔所发展的一种排序算法。在平均状况下,排序 n 个项目要 Ο(nlogn) 次比较。在最坏状况下则需要 Ο(n2) 次比较,但这种状况并不常见。事实上,快速排序通常明显比其他 Ο(nlogn) 算法更快,因为它的内部循环(inner loop)可以在大部分的架构上很有效率地被实现出来。 - -快速排序使用分治法(Divide and conquer)策略来把一个串行(list)分为两个子串行(sub-lists)。 - -快速排序又是一种分而治之思想在排序算法上的典型应用。本质上来看,快速排序应该算是在冒泡排序基础上的递归分治法。 - -快速排序的名字起的是简单粗暴,因为一听到这个名字你就知道它存在的意义,就是快,而且效率高!它是处理大数据最快的排序算法之一了。虽然 Worst Case 的时间复杂度达到了 O(n²),但是人家就是优秀,在大多数情况下都比平均时间复杂度为 O(n logn) 的排序算法表现要更好,可是这是为什么呢,我也不知道。好在我的强迫症又犯了,查了 N 多资料终于在《算法艺术与信息学竞赛》上找到了满意的答案: - -> 快速排序的最坏运行情况是 O(n²),比如说顺序数列的快排。但它的平摊期望时间是 O(nlogn),且 O(nlogn) 记号中隐含的常数因子很小,比复杂度稳定等于 O(nlogn) 的归并排序要小很多。所以,对绝大多数顺序性较弱的随机数列而言,快速排序总是优于归并排序。 - - -## 1. 算法步骤 - -1. 从数列中挑出一个元素,称为 “基准”(pivot); - -2. 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作; - -3. 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序; - -递归的最底部情形,是数列的大小是零或一,也就是永远都已经被排序好了。虽然一直递归下去,但是这个算法总会退出,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。 - - -## 2. 动图演示 - -![动图演示](res/quickSort.gif) - - -## 3. JavaScript 代码实现 - -```js -function quickSort(arr, left, right) { - var len = arr.length, - partitionIndex, - left = typeof left != 'number' ? 0 : left, - right = typeof right != 'number' ? len - 1 : right; - - if (left < right) { - partitionIndex = partition(arr, left, right); - quickSort(arr, left, partitionIndex-1); - quickSort(arr, partitionIndex+1, right); - } - return arr; -} - -function partition(arr, left ,right) { // 分区操作 - var pivot = left, // 设定基准值(pivot) - index = pivot + 1; - for (var i = index; i <= right; i++) { - if (arr[i] < arr[pivot]) { - swap(arr, i, index); - index++; - } - } - swap(arr, pivot, index - 1); - return index-1; -} - -function swap(arr, i, j) { - var temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; -} -functiion paritition2(arr, low, high) { - let pivot = arr[low]; - while (low < high) { - while (low < high && arr[high] > pivot) { - --high; - } - arr[low] = arr[high]; - while (low < high && arr[low] <= pivot) { - ++low; - } - arr[high] = arr[low]; - } - arr[low] = pivot; - return low; -} - -function quickSort2(arr, low, high) { - if (low < high) { - let pivot = paritition2(arr, low, high); - quickSort2(arr, low, pivot - 1); - quickSort2(arr, pivot + 1, high); - } - return arr; -} - -``` - - -## 4. Python 代码实现 - -```python -def quickSort(arr, left=None, right=None): - left = 0 if not isinstance(left,(int, float)) else left - right = len(arr)-1 if not isinstance(right,(int, float)) else right - if left < right: - partitionIndex = partition(arr, left, right) - quickSort(arr, left, partitionIndex-1) - quickSort(arr, partitionIndex+1, right) - return arr - -def partition(arr, left, right): - pivot = left - index = pivot+1 - i = index - while i <= right: - if arr[i] < arr[pivot]: - swap(arr, i, index) - index+=1 - i+=1 - swap(arr,pivot,index-1) - return index-1 - -def swap(arr, i, j): - arr[i], arr[j] = arr[j], arr[i] -``` - -## 5. Go 代码实现 - -```go -func quickSort(arr []int) []int { - return _quickSort(arr, 0, len(arr)-1) -} - -func _quickSort(arr []int, left, right int) []int { - if left < right { - partitionIndex := partition(arr, left, right) - _quickSort(arr, left, partitionIndex-1) - _quickSort(arr, partitionIndex+1, right) - } - return arr -} - -func partition(arr []int, left, right int) int { - pivot := left - index := pivot + 1 - - for i := index; i <= right; i++ { - if arr[i] < arr[pivot] { - swap(arr, i, index) - index += 1 - } - } - swap(arr, pivot, index-1) - return index - 1 -} - -func swap(arr []int, i, j int) { - arr[i], arr[j] = arr[j], arr[i] -} -``` - -## 6. C++版 - - -```C++ - //严蔚敏《数据结构》标准分割函数 - Paritition1(int A[], int low, int high) { - int pivot = A[low]; - while (low < high) { - while (low < high && A[high] >= pivot) { - --high; - } - A[low] = A[high]; - while (low < high && A[low] <= pivot) { - ++low; - } - A[high] = A[low]; - } - A[low] = pivot; - return low; - } - - void QuickSort(int A[], int low, int high) //快排母函数 - { - if (low < high) { - int pivot = Paritition1(A, low, high); - QuickSort(A, low, pivot - 1); - QuickSort(A, pivot + 1, high); - } - } -``` diff --git a/7.heapSort.md b/7.heapSort.md deleted file mode 100644 index d4bfa49..0000000 --- a/7.heapSort.md +++ /dev/null @@ -1,149 +0,0 @@ -# 堆排序 - -堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。堆排序可以说是一种利用堆的概念来排序的选择排序。分为两种方法: - -1. 大顶堆:每个节点的值都大于或等于其子节点的值,在堆排序算法中用于升序排列; -2. 小顶堆:每个节点的值都小于或等于其子节点的值,在堆排序算法中用于降序排列; - -堆排序的平均时间复杂度为 Ο(nlogn)。 - - -## 1. 算法步骤 - -1. 创建一个堆 H[0……n-1]; - -2. 把堆首(最大值)和堆尾互换; - -3. 把堆的尺寸缩小 1,并调用 shift_down(0),目的是把新的数组顶端数据调整到相应位置; - -4. 重复步骤 2,直到堆的尺寸为 1。 - - -## 2. 动图演示 - -![动图演示](res/heapSort.gif) - - -## 3. JavaScript 代码实现 - -```js -var len; // 因为声明的多个函数都需要数据长度,所以把len设置成为全局变量 - -function buildMaxHeap(arr) { // 建立大顶堆 - len = arr.length; - for (var i = Math.floor(len/2); i >= 0; i--) { - heapify(arr, i); - } -} - -function heapify(arr, i) { // 堆调整 - var left = 2 * i + 1, - right = 2 * i + 2, - largest = i; - - if (left < len && arr[left] > arr[largest]) { - largest = left; - } - - if (right < len && arr[right] > arr[largest]) { - largest = right; - } - - if (largest != i) { - swap(arr, i, largest); - heapify(arr, largest); - } -} - -function swap(arr, i, j) { - var temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; -} - -function heapSort(arr) { - buildMaxHeap(arr); - - for (var i = arr.length-1; i > 0; i--) { - swap(arr, 0, i); - len--; - heapify(arr, 0); - } - return arr; -} -``` -## 4. Python 代码实现 - -```python -def buildMaxHeap(arr): - import math - for i in range(math.floor(len(arr)/2),-1,-1): - heapify(arr,i) - -def heapify(arr, i): - left = 2*i+1 - right = 2*i+2 - largest = i - if left < arrLen and arr[left] > arr[largest]: - largest = left - if right < arrLen and arr[right] > arr[largest]: - largest = right - - if largest != i: - swap(arr, i, largest) - heapify(arr, largest) - -def swap(arr, i, j): - arr[i], arr[j] = arr[j], arr[i] - -def heapSort(arr): - global arrLen - arrLen = len(arr) - buildMaxHeap(arr) - for i in range(len(arr)-1,0,-1): - swap(arr,0,i) - arrLen -=1 - heapify(arr, 0) -    return arr -``` - -## 5. Go 代码实现 - -```go -func heapSort(arr []int) []int { - arrLen := len(arr) - buildMaxHeap(arr, arrLen) - for i := arrLen - 1; i >= 0; i-- { - swap(arr, 0, i) - arrLen -= 1 - heapify(arr, 0, arrLen) - } - return arr -} - -func buildMaxHeap(arr []int, arrLen int) { - for i := arrLen / 2; i >= 0; i-- { - heapify(arr, i, arrLen) - } -} - -func heapify(arr []int, i, arrLen int) { - left := 2*i + 1 - right := 2*i + 2 - largest := i - if left < arrLen && arr[left] > arr[largest] { - largest = left - } - if right < arrLen && arr[right] > arr[largest] { - largest = right - } - if largest != i { - swap(arr, i, largest) - heapify(arr, largest, arrLen) - } -} - -func swap(arr []int, i, j int) { - arr[i], arr[j] = arr[j], arr[i] -} -``` diff --git a/8.countingSort.md b/8.countingSort.md deleted file mode 100644 index 164d3ac..0000000 --- a/8.countingSort.md +++ /dev/null @@ -1,82 +0,0 @@ -# 计数排序 - -计数排序的核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。 - -## 1. 动图演示 - -![动图演示](res/countingSort.gif) - - -## 2. JavaScript 代码实现 - -```js -function countingSort(arr, maxValue) { - var bucket = new Array(maxValue+1), - sortedIndex = 0; - arrLen = arr.length, - bucketLen = maxValue + 1; - - for (var i = 0; i < arrLen; i++) { - if (!bucket[arr[i]]) { - bucket[arr[i]] = 0; - } - bucket[arr[i]]++; - } - - for (var j = 0; j < bucketLen; j++) { - while(bucket[j] > 0) { - arr[sortedIndex++] = j; - bucket[j]--; - } - } - - return arr; -} -``` - -## 3. Python 代码实现 - - -```python -def countingSort(arr, maxValue): - bucketLen = maxValue+1 - bucket = [0]*bucketLen - sortedIndex =0 - arrLen = len(arr) - for i in range(arrLen): - if not bucket[arr[i]]: - bucket[arr[i]]=0 - bucket[arr[i]]+=1 - for j in range(bucketLen): - while bucket[j]>0: - arr[sortedIndex] = j - sortedIndex+=1 - bucket[j]-=1 - return arr -``` - -## 4. Go 代码实现 - -```go -func countingSort(arr []int, maxValue int) []int { - bucketLen := maxValue + 1 - bucket := make([]int, bucketLen) // 初始为0的数组 - - sortedIndex := 0 - length := len(arr) - - for i := 0; i < length; i++ { - bucket[arr[i]] += 1 - } - - for j := 0; j < bucketLen; j++ { - for bucket[j] > 0 { - arr[sortedIndex] = j - sortedIndex += 1 - bucket[j] -= 1 - } - } - - return arr -} -``` diff --git a/9.bucketSort.md b/9.bucketSort.md deleted file mode 100644 index 30966f4..0000000 --- a/9.bucketSort.md +++ /dev/null @@ -1,64 +0,0 @@ -# 桶排序 - -桶排序是计数排序的升级版。它利用了函数的映射关系,高效与否的关键就在于这个映射函数的确定。为了使桶排序更加高效,我们需要做到这两点: - -1. 在额外空间充足的情况下,尽量增大桶的数量 -2. 使用的映射函数能够将输入的 N 个数据均匀的分配到 K 个桶中 - -同时,对于桶中元素的排序,选择何种比较排序算法对于性能的影响至关重要。 - - -## 1. 什么时候最快 - -当输入的数据可以均匀的分配到每一个桶中。 - - -## 2. 什么时候最慢 - -当输入的数据被分配到了同一个桶中。 - - -## 3. JavaScript 代码实现 - -```js -function bucketSort(arr, bucketSize) { - if (arr.length === 0) { - return arr; - } - - var i; - var minValue = arr[0]; - var maxValue = arr[0]; - for (i = 1; i < arr.length; i++) { - if (arr[i] < minValue) { - minValue = arr[i]; // 输入数据的最小值 - } else if (arr[i] > maxValue) { - maxValue = arr[i]; // 输入数据的最大值 - } - } - - //桶的初始化 - var DEFAULT_BUCKET_SIZE = 5; // 设置桶的默认数量为5 - bucketSize = bucketSize || DEFAULT_BUCKET_SIZE; - var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; - var buckets = new Array(bucketCount); - for (i = 0; i < buckets.length; i++) { - buckets[i] = []; - } - - //利用映射函数将数据分配到各个桶中 - for (i = 0; i < arr.length; i++) { - buckets[Math.floor((arr[i] - minValue) / bucketSize)].push(arr[i]); - } - - arr.length = 0; - for (i = 0; i < buckets.length; i++) { - insertionSort(buckets[i]); // 对每个桶进行排序,这里使用了插入排序 - for (var j = 0; j < buckets[i].length; j++) { - arr.push(buckets[i][j]); - } - } - - return arr; -} -``` \ No newline at end of file diff --git a/README.md b/README.md index a14f9c1..85ef452 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,10 @@ # 十大经典排序算法 -[![Build Status](https://travis-ci.org/hustcc/JS-Sorting-Algorithm.svg?branch=master)](https://travis-ci.org/hustcc/JS-Sorting-Algorithm) - 排序算法是《数据结构与算法》中最基本的算法之一。 排序算法可以分为内部排序和外部排序,内部排序是数据记录在内存中进行排序,而外部排序是因排序的数据很大,一次不能容纳全部的排序记录,在排序过程中需要访问外存。常见的内部排序算法有:**插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序**等。用一张图概括: -![十大经典排序算法 概览截图](res/sort.png) +![十大经典排序算法 概览截图](https://github.com/slugphp/PHP-Sorting-Algorithm/raw/master/res/sort.png) **关于时间复杂度**: @@ -40,28 +38,25 @@ **稳定性**:排序后 2 个相等键值的顺序和排序之前它们的顺序相同 ----- -**GitBook 内容大纲** +### GitBook 内容大纲 -1. [冒泡排序](1.bubbleSort.md) -2. [选择排序](2.selectionSort.md) -3. [插入排序](3.insertionSort.md) -4. [希尔排序](4.shellSort.md) -5. [归并排序](5.mergeSort.md) -6. [快速排序](6.quickSort.md) -7. [堆排序](7.heapSort.md) -8. [计数排序](8.countingSort.md) -9. [桶排序](9.bucketSort.md) +1. [冒泡排序](01.bubbleSort.md) +2. [选择排序](02.selectionSort.md) +3. [插入排序](03.insertionSort.md) +4. [希尔排序](04.shellSort.md) +5. [归并排序](05.mergeSort.md) +6. [快速排序](06.quickSort.md) +7. [堆排序](07.heapSort.md) +8. [计数排序](08.countingSort.md) +9. [桶排序](09.bucketSort.md) 10. [基数排序](10.radixSort.md) ----- -本书内容几乎完全来源于网络。 +### PHP 代码测试 +`php src/phpSortTest.php` -开源项目地址:[https://github.com/hustcc/JS-Sorting-Algorithm](https://github.com/hustcc/JS-Sorting-Algorithm),整理人 [hustcc](https://github.com/hustcc)。 - -GitBook 在线阅读地址:[https://sort.hust.cc/](https://sort.hust.cc/)。 +---- -本项目使用 [hint](https://github.com/hustcc/hint) 进行中文 Markdown 文件的格式检查,务必在提交 Pr 之前,保证 Markdown 格式正确。 +Forked from [hustcc/JS-Sorting-Algorithm](https://github.com/hustcc/JS-Sorting-Algorithm) diff --git a/src/phpSortTest.php b/src/phpSortTest.php new file mode 100644 index 0000000..03106be --- /dev/null +++ b/src/phpSortTest.php @@ -0,0 +1,299 @@ + + */ + +function sortTest($func, $total = 5000) +{ + global $arr; + if (empty($arr)) { + $arr = range(1, $total); + echo "Verify sort md5: ", substr(md5(json_encode($arr)), 0, 8), "\r\n"; + shuffle($arr); + } + list($m1, $n1) = explode(' ', microtime()); + $res = $func($arr); + list($m2, $n2) = explode(' ', microtime()); + $time = round(($m2 - $m1) + ($n2 - $n1), 6); + echo " $func {$time}s " . substr(md5(json_encode($res)), 0, 8) . "\r\n"; +} + +function bubbleSort($arr) +{ + $len = count($arr); + for ($i = 0; $i < $len; $i++) { + for ($j = 0; $j < $len - 1 - $i; $j++) { + if ($arr[$j] > $arr[$j+1]) { + $tmp = $arr[$j]; + $arr[$j] = $arr[$j+1]; + $arr[$j+1] = $tmp; + } + } + } + return $arr; +} + +function selectionSort($arr) +{ + $len = count($arr); + for ($i = 0; $i < $len - 1; $i++) { + $minIndex = $i; + for ($j = $i + 1; $j < $len; $j++) { + if ($arr[$j] < $arr[$minIndex]) { + $minIndex = $j; + } + } + $temp = $arr[$i]; + $arr[$i] = $arr[$minIndex]; + $arr[$minIndex] = $temp; + } + return $arr; +} + +function insertionSort($arr) +{ + $len = count($arr); + for ($i = 1; $i < $len; $i++) { + $preIndex = $i - 1; + $current = $arr[$i]; + while($preIndex >= 0 && $arr[$preIndex] > $current) { + $arr[$preIndex+1] = $arr[$preIndex]; + $preIndex--; + } + $arr[$preIndex+1] = $current; + } + return $arr; +} + +function shellSort($arr) +{ + $len = count($arr); + $temp = 0; + $gap = 1; + while($gap < $len / 3) { + $gap = $gap * 3 + 1; + } + for ($gap; $gap > 0; $gap = floor($gap / 3)) { + for ($i = $gap; $i < $len; $i++) { + $temp = $arr[$i]; + for ($j = $i - $gap; $j >= 0 && $arr[$j] > $temp; $j -= $gap) { + $arr[$j+$gap] = $arr[$j]; + } + $arr[$j+$gap] = $temp; + } + } + return $arr; +} + +function mergeSort($arr) +{ + $len = count($arr); + if ($len < 2) { + return $arr; + } + $middle = floor($len / 2); + $left = array_slice($arr, 0, $middle); + $right = array_slice($arr, $middle); + return merge(mergeSort($left), mergeSort($right)); +} + +function merge($left, $right) +{ + $result = []; + + while (count($left) > 0 && count($right) > 0) { + if ($left[0] <= $right[0]) { + $result[] = array_shift($left); + } else { + $result[] = array_shift($right); + } + } + + while (count($left)) + $result[] = array_shift($left); + + while (count($right)) + $result[] = array_shift($right); + + return $result; +} + +function quickSort($arr) +{ + if (count($arr) <= 1) + return $arr; + $middle = $arr[0]; + $leftArray = array(); + $rightArray = array(); + + for ($i = 1; $i < count($arr); $i++) { + if ($arr[$i] > $middle) + $rightArray[] = $arr[$i]; + else + $leftArray[] = $arr[$i]; + } + $leftArray = quickSort($leftArray); + $leftArray[] = $middle; + + $rightArray = quickSort($rightArray); + return array_merge($leftArray, $rightArray); +} + + +function buildMaxHeap(&$arr) +{ + global $len; + for ($i = floor($len/2); $i >= 0; $i--) { + heapify($arr, $i); + } +} + +function heapify(&$arr, $i) +{ + global $len; + $left = 2 * $i + 1; + $right = 2 * $i + 2; + $largest = $i; + + if ($left < $len && $arr[$left] > $arr[$largest]) { + $largest = $left; + } + + if ($right < $len && $arr[$right] > $arr[$largest]) { + $largest = $right; + } + + if ($largest != $i) { + swap($arr, $i, $largest); + heapify($arr, $largest); + } +} + +function swap(&$arr, $i, $j) +{ + $temp = $arr[$i]; + $arr[$i] = $arr[$j]; + $arr[$j] = $temp; +} + +function heapSort($arr) { + global $len; + $len = count($arr); + buildMaxHeap($arr); + for ($i = count($arr) - 1; $i > 0; $i--) { + swap($arr, 0, $i); + $len--; + heapify($arr, 0); + } + return $arr; +} + +function countingSort($arr, $maxValue = null) +{ + if ($maxValue === null) { + $maxValue = max($arr); + } + for ($m = 0; $m < $maxValue + 1; $m++) { + $bucket[] = null; + } + + $arrLen = count($arr); + for ($i = 0; $i < $arrLen; $i++) { + if (!array_key_exists($arr[$i], $bucket)) { + $bucket[$arr[$i]] = 0; + } + $bucket[$arr[$i]]++; + } + + $sortedIndex = 0; + foreach ($bucket as $key => $len) { + if ($len !== null) $arr[$sortedIndex++] = $key; + } + + return $arr; +} + +function bucketSort($arr, $bucketSize = 5) +{ + if (count($arr) === 0) { + return $arr; + } + + $minValue = $arr[0]; + $maxValue = $arr[0]; + for ($i = 1; $i < count($arr); $i++) { + if ($arr[$i] < $minValue) { + $minValue = $arr[$i]; + } else if ($arr[$i] > $maxValue) { + $maxValue = $arr[$i]; + } + } + + $bucketCount = floor(($maxValue - $minValue) / $bucketSize) + 1; + $buckets = array(); + for ($i = 0; $i < count($buckets); $i++) { + $buckets[$i] = []; + } + + for ($i = 0; $i < count($arr); $i++) { + $buckets[floor(($arr[$i] - $minValue) / $bucketSize)][] = $arr[$i]; + } + + $arr = array(); + for ($i = 0; $i < count($buckets); $i++) { + $bucketTmp = $buckets[$i]; + sort($bucketTmp); + for ($j = 0; $j < count($bucketTmp); $j++) { + $arr[] = $bucketTmp[$j]; + } + } + + return $arr; +} + +function radixSort($arr, $maxDigit = null) +{ + if ($maxDigit === null) { + $maxDigit = max($arr); + } + $counter = []; + for ($i = 0; $i < $maxDigit; $i++) { + for ($j = 0; $j < count($arr); $j++) { + preg_match_all('/\d/', (string) $arr[$j], $matches); + $numArr = $matches[0]; + $lenTmp = count($numArr); + $bucket = array_key_exists($lenTmp - $i - 1, $numArr) + ? intval($numArr[$lenTmp - $i - 1]) + : 0; + if (!array_key_exists($bucket, $counter)) { + $counter[$bucket] = []; + } + $counter[$bucket][] = $arr[$j]; + } + $pos = 0; + for ($j = 0; $j < count($counter); $j++) { + $value = null; + if ($counter[$j] !== null) { + while (($value = array_shift($counter[$j])) !== null) { + $arr[$pos++] = $value; + } + } + } + } + + return $arr; +} + +$total = 2000; + +sortTest('bubbleSort', $total); +sortTest('selectionSort', $total); +sortTest('insertionSort', $total); +sortTest('shellSort', $total); +sortTest('mergeSort', $total); +sortTest('quickSort', $total); +sortTest('heapSort', $total); +sortTest('countingSort', $total); +sortTest('bucketSort', $total); +sortTest('radixSort', $total); diff --git a/test/pythonSortTest.py b/test/pythonSortTest.py deleted file mode 100644 index eb5b137..0000000 --- a/test/pythonSortTest.py +++ /dev/null @@ -1,165 +0,0 @@ -''' -# Create by LokiSharp(loki.sharp#gmail) at 2017-1-22 -''' - -TOTAL=5000 - -def sortTest(func, total=1000): - import random, copy, operator, math, time - arrList = [i for i in range(-math.floor(total/2),math.ceil(total/2))] - arrListR = copy.deepcopy(arrList) - while operator.eq(arrList,arrListR): - random.shuffle(arrListR) - #print("--- [Origin List]", arrList, "Use", func.__name__,"with Total:", len(arrList)) - #print("--> [Random List]", arrListR, "Use", func.__name__,"with Total:", len(arrList)) - start = time.clock() - arrListR = func(arrListR) - end = time.clock() - runtime = end-start - #print("--> [Sorted List]", arrListR, "Use", func.__name__,"with Total:", len(arrList)) - if operator.eq(arrList, arrListR): - print("[Success]", func.__name__,"with Total:", len(arrList),"in %.5fs" % runtime) - return True - else: - print("[Fail]", func.__name__,"with Total:", len(arrList),"in %.5fs" % runtime) - return False - -def bubbleSort(arr): - for i in range(1, len(arr)): - for j in range(0, len(arr)-i): - if arr[j] > arr[j+1]: - arr[j], arr[j + 1] = arr[j + 1], arr[j] - return arr - -def selectionSort(arr): - for i in range(len(arr)-1): - for j in range(i+1, len(arr)): - if arr[j] < arr[i]: - arr[i], arr[j] = arr[j], arr[i] - return arr - -def insertionSort(arr): - for i in range(len(arr)): - preIndex = i-1 - current = arr[i] - while preIndex >= 0 and arr[preIndex] > current: - arr[preIndex+1] = arr[preIndex] - preIndex-=1 - arr[preIndex+1] = current - return arr - -def shellSort(arr): - import math - gap=1 - while(gap < len(arr)/3): - gap = gap*3+1 - 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 = math.floor(gap/3) - return arr - -def mergeSort(arr): - import math - if(len(arr)<2): - return arr - middle = math.floor(len(arr)/2) - left, right = arr[0:middle], arr[middle:] - return merge(mergeSort(left), mergeSort(right)) - -def merge(left,right): - result = [] - while left and right: - if left[0] <= right[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)); - return result - -def quickSort(arr, left=None, right=None): - left = 0 if not isinstance(left,(int, float)) else left - right = len(arr)-1 if not isinstance(right,(int, float)) else right - if left < right: - partitionIndex = partition(arr, left, right) - quickSort(arr, left, partitionIndex-1) - quickSort(arr, partitionIndex+1, right) - return arr - -def partition(arr, left, right): - pivot = left - index = pivot+1 - i = index - while i <= right: - if arr[i] < arr[pivot]: - swap(arr, i, index) - index+=1 - i+=1 - swap(arr,pivot,index-1) - return index-1 - -def swap(arr, i, j): - arr[i], arr[j] = arr[j], arr[i] - -def buildMaxHeap(arr): - import math - for i in range(math.floor(len(arr)/2),-1,-1): - heapify(arr,i) - -def heapify(arr, i): - left = 2*i+1 - right = 2*i+2 - largest = i - if left < arrLen and arr[left] > arr[largest]: - largest = left - if right < arrLen and arr[right] > arr[largest]: - largest = right - - if largest != i: - swap(arr, i, largest) - heapify(arr, largest) - -def swap(arr, i, j): - arr[i], arr[j] = arr[j], arr[i] - -def heapSort(arr): - global arrLen - arrLen = len(arr) - buildMaxHeap(arr) - for i in range(len(arr)-1,0,-1): - swap(arr,0,i) - arrLen -=1 - heapify(arr, 0) - return arr - -def countingSort(arr, maxValue=None): - bucketLen = maxValue+1 - bucket = [0]*bucketLen - sortedIndex =0 - arrLen = len(arr) - for i in range(arrLen): - if not bucket[arr[i]]: - bucket[arr[i]]=0 - bucket[arr[i]]+=1 - for j in range(bucketLen): - while bucket[j]>0: - arr[sortedIndex] = j - sortedIndex+=1 - bucket[j]-=1 - return arr - -sortTest(bubbleSort, TOTAL) -sortTest(selectionSort, TOTAL) -sortTest(insertionSort, TOTAL) -sortTest(shellSort, TOTAL) -sortTest(mergeSort, TOTAL) -sortTest(quickSort, TOTAL) -sortTest(heapSort, TOTAL) From 207a1cd3b31b3148283680e99475149109e1e235 Mon Sep 17 00:00:00 2001 From: wilon Date: Mon, 26 Jun 2017 17:00:42 +0800 Subject: [PATCH 2/3] code psr --- 03.insertionSort.md | 3 ++- 04.shellSort.md | 3 ++- 05.mergeSort.md | 4 ++-- 08.countingSort.md | 1 - 09.bucketSort.md | 1 - 10.radixSort.md | 1 - 6 files changed, 6 insertions(+), 7 deletions(-) diff --git a/03.insertionSort.md b/03.insertionSort.md index e184097..faca923 100644 --- a/03.insertionSort.md +++ b/03.insertionSort.md @@ -20,7 +20,8 @@ ## 3. PHP 代码实现 ```php -function insertionSort($arr) { +function insertionSort($arr) +{ $len = count($arr); for ($i = 1; $i < $len; $i++) { $preIndex = $i - 1; diff --git a/04.shellSort.md b/04.shellSort.md index 0f77c12..112441b 100644 --- a/04.shellSort.md +++ b/04.shellSort.md @@ -22,7 +22,8 @@ ## 2. PHP 代码实现 ```php -function shellSort($arr) { +function shellSort($arr) +{ $len = count($arr); $temp = 0; $gap = 1; diff --git a/05.mergeSort.md b/05.mergeSort.md index edeb58f..5a627bd 100644 --- a/05.mergeSort.md +++ b/05.mergeSort.md @@ -39,7 +39,8 @@ ## 4. PHP 代码实现 ```php -function mergeSort($arr) { +function mergeSort($arr) +{ $len = count($arr); if ($len < 2) { return $arr; @@ -70,5 +71,4 @@ function merge($left, $right) return $result; } - ``` diff --git a/08.countingSort.md b/08.countingSort.md index d3b6557..41075e0 100644 --- a/08.countingSort.md +++ b/08.countingSort.md @@ -10,7 +10,6 @@ ## 2. PHP 代码实现 ```php - function countingSort($arr, $maxValue = null) { if ($maxValue === null) { diff --git a/09.bucketSort.md b/09.bucketSort.md index 1369110..bab5978 100644 --- a/09.bucketSort.md +++ b/09.bucketSort.md @@ -21,7 +21,6 @@ ## 3. PHP 代码实现 ```php - function bucketSort($arr, $bucketSize = 5) { if (count($arr) === 0) { diff --git a/10.radixSort.md b/10.radixSort.md index 3277bf4..bbd56e8 100644 --- a/10.radixSort.md +++ b/10.radixSort.md @@ -22,7 +22,6 @@ ## 3. PHP 代码实现 ```php - function radixSort($arr, $maxDigit = null) { if ($maxDigit === null) { From ce2cb8f2bbb67a9e056a112b66844ed52a7824e3 Mon Sep 17 00:00:00 2001 From: wilon Date: Mon, 26 Jun 2017 17:04:07 +0800 Subject: [PATCH 3/3] summary --- SUMMARY.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/SUMMARY.md b/SUMMARY.md index 8b44f52..8c86015 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -1,12 +1,12 @@ # Summary -1. [冒泡排序](1.bubbleSort.md) -2. [选择排序](2.selectionSort.md) -3. [插入排序](3.insertionSort.md) -4. [希尔排序](4.shellSort.md) -5. [归并排序](5.mergeSort.md) -6. [快速排序](6.quickSort.md) -7. [堆排序](7.heapSort.md) -8. [计数排序](8.countingSort.md) -9. [桶排序](9.bucketSort.md) +1. [冒泡排序](01.bubbleSort.md) +2. [选择排序](02.selectionSort.md) +3. [插入排序](03.insertionSort.md) +4. [希尔排序](04.shellSort.md) +5. [归并排序](05.mergeSort.md) +6. [快速排序](06.quickSort.md) +7. [堆排序](07.heapSort.md) +8. [计数排序](08.countingSort.md) +9. [桶排序](09.bucketSort.md) 10. [基数排序](10.radixSort.md)