diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..6e86d35 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: ['https://paypal.me/hustcc', 'https://atool.vip'] diff --git a/.gitignore b/.gitignore index 1a366fb..f6cbc5f 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,9 @@ _book # eBook build output *.epub *.mobi -*.pdf \ No newline at end of file +*.pdf +\.idea/ + +*.iml + +src/javaSortTest/target/ diff --git a/.travis.yml b/.travis.yml index b2b108c..2b6c65f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,6 @@ -sudo: required -language: python -python: - - "2.7" +language: node_js +node_js: + - "10" before_install: - - pip install hint -script: - - hint . \ No newline at end of file + - npm i -g lint-md-cli +script: lint-md ./ diff --git a/1.bubbleSort.md b/1.bubbleSort.md index e53a38d..78c3b83 100644 --- a/1.bubbleSort.md +++ b/1.bubbleSort.md @@ -77,3 +77,55 @@ func bubbleSort(arr []int) []int { return arr } ``` + +## 8. Java 代码实现 + +```java +public class BubbleSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + for (int i = 1; i < arr.length; i++) { + // 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。 + boolean flag = true; + + for (int j = 0; j < arr.length - i; j++) { + if (arr[j] > arr[j + 1]) { + int tmp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = tmp; + + flag = false; + } + } + + if (flag) { + break; + } + } + return arr; + } +} +``` + +## 9. 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; +} +``` diff --git a/10.radixSort.md b/10.radixSort.md index 5f40ea7..2da94b8 100644 --- a/10.radixSort.md +++ b/10.radixSort.md @@ -7,7 +7,7 @@ 基数排序有两种方法: -这三种排序算法都利用了桶的概念,但对桶的使用方法上有明显差异: +这三种排序算法都利用了桶的概念,但对桶的使用方法上有明显差异案例看大家发的: - 基数排序:根据键值的每位数字来分配桶; - 计数排序:每个桶只存储单一键值; @@ -47,4 +47,158 @@ function radixSort(arr, maxDigit) { } return arr; } -``` \ No newline at end of file +``` + + +## 4. python 代码实现 + +```python +def radix(arr): + + digit = 0 + max_digit = 1 + max_value = max(arr) + #找出列表中最大的位数 + while 10**max_digit < max_value: + max_digit = max_digit + 1 + + while digit < max_digit: + temp = [[] for i in range(10)] + for i in arr: + #求出每一个元素的个、十、百位的值 + t = int((i/10**digit)%10) + temp[t].append(i) + + coll = [] + for bucket in temp: + for i in bucket: + coll.append(i) + + arr = coll + digit = digit + 1 + + return arr +``` + + +## 5. Java 代码实现 + +```java +/** + * 基数排序 + * 考虑负数的情况还可以参考: https://code.i-harness.com/zh-CN/q/e98fa9 + */ +public class RadixSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + int maxDigit = getMaxDigit(arr); + return radixSort(arr, maxDigit); + } + + /** + * 获取最高位数 + */ + private int getMaxDigit(int[] arr) { + int maxValue = getMaxValue(arr); + return getNumLenght(maxValue); + } + + private int getMaxValue(int[] arr) { + int maxValue = arr[0]; + for (int value : arr) { + if (maxValue < value) { + maxValue = value; + } + } + return maxValue; + } + + protected int getNumLenght(long num) { + if (num == 0) { + return 1; + } + int lenght = 0; + for (long temp = num; temp != 0; temp /= 10) { + lenght++; + } + return lenght; + } + + private int[] radixSort(int[] arr, int maxDigit) { + int mod = 10; + int dev = 1; + + for (int i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) { + // 考虑负数的情况,这里扩展一倍队列数,其中 [0-9]对应负数,[10-19]对应正数 (bucket + 10) + int[][] counter = new int[mod * 2][0]; + + for (int j = 0; j < arr.length; j++) { + int bucket = ((arr[j] % mod) / dev) + mod; + counter[bucket] = arrayAppend(counter[bucket], arr[j]); + } + + int pos = 0; + for (int[] bucket : counter) { + for (int value : bucket) { + arr[pos++] = value; + } + } + } + + return arr; + } + + /** + * 自动扩容,并保存数据 + * + * @param arr + * @param value + */ + private int[] arrayAppend(int[] arr, int value) { + arr = Arrays.copyOf(arr, arr.length + 1); + arr[arr.length - 1] = value; + return arr; + } +} +``` + +## 6. 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][] = $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; +} +``` diff --git a/2.selectionSort.md b/2.selectionSort.md index 1c3ddbc..103830e 100644 --- a/2.selectionSort.md +++ b/2.selectionSort.md @@ -42,10 +42,15 @@ function selectionSort(arr) { ```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] + for i in range(len(arr) - 1): + # 记录最小数的索引 + minIndex = i + for j in range(i + 1, len(arr)): + if arr[j] < arr[minIndex]: + minIndex = j + # i 不是最小数时,将 i 和最小数进行交换 + if i != minIndex: + arr[i], arr[minIndex] = arr[minIndex], arr[i] return arr ``` @@ -66,3 +71,58 @@ func selectionSort(arr []int) []int { return arr } ``` + +## 6. Java 代码实现 + +```java +public class SelectionSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + // 总共要经过 N-1 轮比较 + for (int i = 0; i < arr.length - 1; i++) { + int min = i; + + // 每轮需要比较的次数 N-i + for (int j = i + 1; j < arr.length; j++) { + if (arr[j] < arr[min]) { + // 记录目前能找到的最小值元素的下标 + min = j; + } + } + + // 将找到的最小值和i位置所在的值进行交换 + if (i != min) { + int tmp = arr[i]; + arr[i] = arr[min]; + arr[min] = tmp; + } + + } + return arr; + } +} +``` + +## 7. 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/3.insertionSort.md b/3.insertionSort.md index 11ed672..c828cb3 100644 --- a/3.insertionSort.md +++ b/3.insertionSort.md @@ -65,3 +65,56 @@ func insertionSort(arr []int) []int { return arr } ``` + +## 6. Java 代码实现 + +```java +public class InsertSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + // 从下标为1的元素开始选择合适的位置插入,因为下标为0的只有一个元素,默认是有序的 + for (int i = 1; i < arr.length; i++) { + + // 记录要插入的数据 + int tmp = arr[i]; + + // 从已经排序的序列最右边的开始比较,找到比其小的数 + int j = i; + while (j > 0 && tmp < arr[j - 1]) { + arr[j] = arr[j - 1]; + j--; + } + + // 存在比其小的数,插入 + if (j != i) { + arr[j] = tmp; + } + + } + return arr; + } +} +``` + +## 7. 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/4.shellSort.md b/4.shellSort.md index 0406030..e6d5f9c 100644 --- a/4.shellSort.md +++ b/4.shellSort.md @@ -69,7 +69,7 @@ def shellSort(arr): func shellSort(arr []int) []int { length := len(arr) gap := 1 - for gap < gap/3 { + for gap < length/3 { gap = gap*3 + 1 } for gap > 0 { @@ -87,3 +87,80 @@ func shellSort(arr []int) []int { return arr } ``` + +## 5. Java 代码实现 + +```java +public class ShellSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + int gap = 1; + while (gap < arr.length/3) { + gap = gap * 3 + 1; + } + + while (gap > 0) { + for (int i = gap; i < arr.length; i++) { + int tmp = arr[i]; + int j = i - gap; + while (j >= 0 && arr[j] > tmp) { + arr[j + gap] = arr[j]; + j -= gap; + } + arr[j + gap] = tmp; + } + gap = (int) Math.floor(gap / 3); + } + + return arr; + } +} +``` + +## 6. 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; +} +``` + +## 7. C++ 代码实现 + +```cpp +void shellSort(vector& arr) { + int gap = 1; + while (gap < (int)arr.size() / 3) { + gap = gap * 3 + 1; + } + for (; gap >= 1; gap /= 3) { + for (int i = 0; i < gap; ++i) { + for (int j = i + gap; j < arr.size(); j += gap) { + for (int k = j; k - gap >= 0 && arr[k] < arr[k - gap]; k -= gap) { + swap(arr[k], arr[k - gap]); + } + } + } + } +} +``` diff --git a/5.mergeSort.md b/5.mergeSort.md index e1e1479..c030d8f 100644 --- a/5.mergeSort.md +++ b/5.mergeSort.md @@ -136,3 +136,127 @@ func merge(left []int, right []int) []int { return result } ``` + +## 7. Java 代码实现 + +```java +public class MergeSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + if (arr.length < 2) { + return arr; + } + int middle = (int) Math.floor(arr.length / 2); + + int[] left = Arrays.copyOfRange(arr, 0, middle); + int[] right = Arrays.copyOfRange(arr, middle, arr.length); + + return merge(sort(left), sort(right)); + } + + protected int[] merge(int[] left, int[] right) { + int[] result = new int[left.length + right.length]; + int i = 0; + while (left.length > 0 && right.length > 0) { + if (left[0] <= right[0]) { + result[i++] = left[0]; + left = Arrays.copyOfRange(left, 1, left.length); + } else { + result[i++] = right[0]; + right = Arrays.copyOfRange(right, 1, right.length); + } + } + + while (left.length > 0) { + result[i++] = left[0]; + left = Arrays.copyOfRange(left, 1, left.length); + } + + while (right.length > 0) { + result[i++] = right[0]; + right = Arrays.copyOfRange(right, 1, right.length); + } + + return result; + } + +} +``` + +## 8. 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; +} +``` + +## 9. C++ 代码实现 + +```cpp +void merge(vector& arr, int l, int mid, int r) { + int index = 0; + int ptrL = l; + int ptrR = mid; + static vectortempary; + if (arr.size() > tempary.size()) { + tempary.resize(arr.size()); + } + while (ptrL != mid && ptrR != r) { + if (arr[ptrL] < arr[ptrR]) { + tempary[index++] = arr[ptrL++]; + } else { + tempary[index++] = arr[ptrR++]; + } + } + while (ptrL != mid) { + tempary[index++] = arr[ptrL++]; + } + while (ptrR != r) { + tempary[index++] = arr[ptrR++]; + } + copy(tempary.begin(), tempary.begin() + index, arr.begin() + l); +} +void mergeSort(vector& arr, int l, int r) { // sort the range [l, r) in arr + if (r - l <= 1) { + return; + } + int mid = (l + r) / 2; + mergeSort(arr, l, mid); + mergeSort(arr, mid, r); + merge(arr, l, mid, r); +} +``` diff --git a/6.quickSort.md b/6.quickSort.md index 1c81c59..28ad477 100644 --- a/6.quickSort.md +++ b/6.quickSort.md @@ -62,7 +62,7 @@ function swap(arr, i, j) { arr[i] = arr[j]; arr[j] = temp; } -functiion paritition2(arr, low, high) { +function partition2(arr, low, high) { let pivot = arr[low]; while (low < high) { while (low < high && arr[high] > pivot) { @@ -80,7 +80,7 @@ functiion paritition2(arr, low, high) { function quickSort2(arr, low, high) { if (low < high) { - let pivot = paritition2(arr, low, high); + let pivot = partition2(arr, low, high); quickSort2(arr, low, pivot - 1); quickSort2(arr, pivot + 1, high); } @@ -177,9 +177,79 @@ func swap(arr []int, i, j int) { void QuickSort(int A[], int low, int high) //快排母函数 { if (low < high) { - int pivot = Paritition1(A, low, high); + int pivot = Paritition1(A, low, high); QuickSort(A, low, pivot - 1); QuickSort(A, pivot + 1, high); } } ``` + +## 7. Java 代码实现 + +```java +public class QuickSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + return quickSort(arr, 0, arr.length - 1); + } + + private int[] quickSort(int[] arr, int left, int right) { + if (left < right) { + int partitionIndex = partition(arr, left, right); + quickSort(arr, left, partitionIndex - 1); + quickSort(arr, partitionIndex + 1, right); + } + return arr; + } + + private int partition(int[] arr, int left, int right) { + // 设定基准值(pivot) + int pivot = left; + int index = pivot + 1; + for (int i = index; i <= right; i++) { + if (arr[i] < arr[pivot]) { + swap(arr, i, index); + index++; + } + } + swap(arr, pivot, index - 1); + return index - 1; + } + + private void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + +} +``` + +## 8. 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/7.heapSort.md b/7.heapSort.md index d4bfa49..394d929 100644 --- a/7.heapSort.md +++ b/7.heapSort.md @@ -10,7 +10,7 @@ ## 1. 算法步骤 -1. 创建一个堆 H[0……n-1]; +1. 将待排序序列构建成一个堆 H[0……n-1],根据(升序降序需求)选择大顶堆或小顶堆; 2. 把堆首(最大值)和堆尾互换; @@ -147,3 +147,111 @@ func swap(arr []int, i, j int) { arr[i], arr[j] = arr[j], arr[i] } ``` + +## 6. Java 代码实现 + +```java +public class HeapSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + int len = arr.length; + + buildMaxHeap(arr, len); + + for (int i = len - 1; i > 0; i--) { + swap(arr, 0, i); + len--; + heapify(arr, 0, len); + } + return arr; + } + + private void buildMaxHeap(int[] arr, int len) { + for (int i = (int) Math.floor(len / 2); i >= 0; i--) { + heapify(arr, i, len); + } + } + + private void heapify(int[] arr, int i, int len) { + int left = 2 * i + 1; + int right = 2 * i + 2; + int 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, len); + } + } + + private void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + +} +``` + +## 7. 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/8.countingSort.md b/8.countingSort.md index 164d3ac..d0930cf 100644 --- a/8.countingSort.md +++ b/8.countingSort.md @@ -80,3 +80,82 @@ func countingSort(arr []int, maxValue int) []int { return arr } ``` + +## 5. Java 代码实现 + +```java +public class CountingSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + int maxValue = getMaxValue(arr); + + return countingSort(arr, maxValue); + } + + private int[] countingSort(int[] arr, int maxValue) { + int bucketLen = maxValue + 1; + int[] bucket = new int[bucketLen]; + + for (int value : arr) { + bucket[value]++; + } + + int sortedIndex = 0; + for (int j = 0; j < bucketLen; j++) { + while (bucket[j] > 0) { + arr[sortedIndex++] = j; + bucket[j]--; + } + } + return arr; + } + + private int getMaxValue(int[] arr) { + int maxValue = arr[0]; + for (int value : arr) { + if (maxValue < value) { + maxValue = value; + } + } + return maxValue; + } + +} +``` + +## 6. 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){ + for($j = 0; $j < $len; $j++){ + $arr[$sortedIndex++] = $key; + } + } + } + + return $arr; +} +``` \ No newline at end of file diff --git a/9.bucketSort.md b/9.bucketSort.md index 30966f4..bd76a63 100644 --- a/9.bucketSort.md +++ b/9.bucketSort.md @@ -61,4 +61,115 @@ function bucketSort(arr, bucketSize) { return arr; } +``` + +## 4. Java 代码实现 + +```java +public class BucketSort implements IArraySort { + + private static final InsertSort insertSort = new InsertSort(); + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + return bucketSort(arr, 5); + } + + private int[] bucketSort(int[] arr, int bucketSize) throws Exception { + if (arr.length == 0) { + return arr; + } + + int minValue = arr[0]; + int maxValue = arr[0]; + for (int value : arr) { + if (value < minValue) { + minValue = value; + } else if (value > maxValue) { + maxValue = value; + } + } + + int bucketCount = (int) Math.floor((maxValue - minValue) / bucketSize) + 1; + int[][] buckets = new int[bucketCount][0]; + + // 利用映射函数将数据分配到各个桶中 + for (int i = 0; i < arr.length; i++) { + int index = (int) Math.floor((arr[i] - minValue) / bucketSize); + buckets[index] = arrAppend(buckets[index], arr[i]); + } + + int arrIndex = 0; + for (int[] bucket : buckets) { + if (bucket.length <= 0) { + continue; + } + // 对每个桶进行排序,这里使用了插入排序 + bucket = insertSort.sort(bucket); + for (int value : bucket) { + arr[arrIndex++] = value; + } + } + + return arr; + } + + /** + * 自动扩容,并保存数据 + * + * @param arr + * @param value + */ + private int[] arrAppend(int[] arr, int value) { + arr = Arrays.copyOf(arr, arr.length + 1); + arr[arr.length - 1] = value; + return arr; + } + +} +``` + +## 5. 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/README.md b/README.md index a14f9c1..4c36daa 100644 --- a/README.md +++ b/README.md @@ -64,4 +64,4 @@ GitBook 在线阅读地址:[https://sort.hust.cc/](https://sort.hust.cc/)。 -本项目使用 [hint](https://github.com/hustcc/hint) 进行中文 Markdown 文件的格式检查,务必在提交 Pr 之前,保证 Markdown 格式正确。 +本项目使用 [lint-md](https://github.com/hustcc/lint-md) 进行中文 Markdown 文件的格式检查,务必在提交 Pr 之前,保证 Markdown 格式正确。 diff --git a/src/java/main/BubbleSort.java b/src/java/main/BubbleSort.java new file mode 100644 index 0000000..3c8cebc --- /dev/null +++ b/src/java/main/BubbleSort.java @@ -0,0 +1,33 @@ +import java.util.Arrays; + +/** + * 冒泡排序 + */ +public class BubbleSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + for (int i = 1; i < arr.length; i++) { + // 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。 + boolean flag = true; + + for (int j = 0; j < arr.length - i; j++) { + if (arr[j] > arr[j + 1]) { + int tmp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = tmp; + + flag = false; + } + } + + if (flag) { + break; + } + } + return arr; + } +} diff --git a/src/java/main/BucketSort.java b/src/java/main/BucketSort.java new file mode 100644 index 0000000..c0b5183 --- /dev/null +++ b/src/java/main/BucketSort.java @@ -0,0 +1,69 @@ +import java.util.Arrays; + +/** + * 桶排序 + */ +public class BucketSort implements IArraySort { + + private static final InsertSort insertSort = new InsertSort(); + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + return bucketSort(arr, 5); + } + + private int[] bucketSort(int[] arr, int bucketSize) throws Exception { + if (arr.length == 0) { + return arr; + } + + int minValue = arr[0]; + int maxValue = arr[0]; + for (int value : arr) { + if (value < minValue) { + minValue = value; + } else if (value > maxValue) { + maxValue = value; + } + } + + int bucketCount = (int) Math.floor((maxValue - minValue) / bucketSize) + 1; + int[][] buckets = new int[bucketCount][0]; + + // 利用映射函数将数据分配到各个桶中 + for (int i = 0; i < arr.length; i++) { + int index = (int) Math.floor((arr[i] - minValue) / bucketSize); + buckets[index] = arrAppend(buckets[index], arr[i]); + } + + int arrIndex = 0; + for (int[] bucket : buckets) { + if (bucket.length <= 0) { + continue; + } + // 对每个桶进行排序,这里使用了插入排序 + bucket = insertSort.sort(bucket); + for (int value : bucket) { + arr[arrIndex++] = value; + } + } + + return arr; + } + + /** + * 自动扩容,并保存数据 + * + * @param arr + * @param value + */ + private int[] arrAppend(int[] arr, int value) { + arr = Arrays.copyOf(arr, arr.length + 1); + arr[arr.length - 1] = value; + return arr; + } + +} diff --git a/src/java/main/CountingSort.java b/src/java/main/CountingSort.java new file mode 100644 index 0000000..74fcd2a --- /dev/null +++ b/src/java/main/CountingSort.java @@ -0,0 +1,46 @@ +import java.util.Arrays; + +/** + * 计数排序 + */ +public class CountingSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + int maxValue = getMaxValue(arr); + + return countingSort(arr, maxValue); + } + + private int[] countingSort(int[] arr, int maxValue) { + int bucketLen = maxValue + 1; + int[] bucket = new int[bucketLen]; + + for (int value : arr) { + bucket[value]++; + } + + int sortedIndex = 0; + for (int j = 0; j < bucketLen; j++) { + while (bucket[j] > 0) { + arr[sortedIndex++] = j; + bucket[j]--; + } + } + return arr; + } + + private int getMaxValue(int[] arr) { + int maxValue = arr[0]; + for (int value : arr) { + if (maxValue < value) { + maxValue = value; + } + } + return maxValue; + } + +} diff --git a/src/java/main/HeapSort.java b/src/java/main/HeapSort.java new file mode 100644 index 0000000..6e9dcfe --- /dev/null +++ b/src/java/main/HeapSort.java @@ -0,0 +1,56 @@ +import java.util.Arrays; + +/** + * 堆排序 + */ +public class HeapSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + int len = arr.length; + + buildMaxHeap(arr, len); + + for (int i = len - 1; i > 0; i--) { + swap(arr, 0, i); + len--; + heapify(arr, 0, len); + } + return arr; + } + + private void buildMaxHeap(int[] arr, int len) { + for (int i = (int) Math.floor(len / 2); i >= 0; i--) { + heapify(arr, i, len); + } + } + + private void heapify(int[] arr, int i, int len) { + int left = 2 * i + 1; + int right = 2 * i + 2; + int 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, len); + } + } + + private void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + +} diff --git a/src/java/main/IArraySort.java b/src/java/main/IArraySort.java new file mode 100644 index 0000000..7d607e5 --- /dev/null +++ b/src/java/main/IArraySort.java @@ -0,0 +1,14 @@ +/** + * Created by corning on 2017/12/19. + */ +public interface IArraySort { + /** + * 对数组进行排序,并返回排序后的数组 + * + * @param sourceArray + * @return + * @throws Exception + */ + int[] sort(int[] sourceArray) throws Exception; + +} diff --git a/src/java/main/InsertSort.java b/src/java/main/InsertSort.java new file mode 100644 index 0000000..1321972 --- /dev/null +++ b/src/java/main/InsertSort.java @@ -0,0 +1,34 @@ +import java.util.Arrays; + +/** + * 插入排序 + */ +public class InsertSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + // 从下标为1的元素开始选择合适的位置插入,因为下标为0的只有一个元素,默认是有序的 + for (int i = 1; i < arr.length; i++) { + + // 记录要插入的数据 + int tmp = arr[i]; + + // 从已经排序的序列最右边的开始比较,找到比其小的数 + int j = i; + while (j > 0 && tmp < arr[j - 1]) { + arr[j] = arr[j - 1]; + j--; + } + + // 存在比其小的数,插入 + if (j != i) { + arr[j] = tmp; + } + + } + return arr; + } +} diff --git a/src/java/main/MergeSort.java b/src/java/main/MergeSort.java new file mode 100644 index 0000000..6457036 --- /dev/null +++ b/src/java/main/MergeSort.java @@ -0,0 +1,50 @@ +import java.util.Arrays; + +/** + * 归并排序 + */ +public class MergeSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + if (arr.length < 2) { + return arr; + } + int middle = (int) Math.floor(arr.length / 2); + + int[] left = Arrays.copyOfRange(arr, 0, middle); + int[] right = Arrays.copyOfRange(arr, middle, arr.length); + + return merge(sort(left), sort(right)); + } + + protected int[] merge(int[] left, int[] right) { + int[] result = new int[left.length + right.length]; + int l = 0, r = 0, len = 0; + while (len < left.length + right.length) { + if (left[l] <= right[r]) { + result[len++] = left[l++]; + + if (l == left.length) { + for (int i = r; i < right.length; i++) { + result[len++] = right[r++]; + } + } + } else { + result[len++] = right[r++]; + + if (r == right.length) { + for (int i = l; i < left.length; i++) { + result[len++] = left[l++]; + } + } + } + } + + return result; + } + +} diff --git a/src/java/main/QuickSort.java b/src/java/main/QuickSort.java new file mode 100644 index 0000000..1c598ed --- /dev/null +++ b/src/java/main/QuickSort.java @@ -0,0 +1,45 @@ +import java.util.Arrays; + +/** + * 快速排序 + */ +public class QuickSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + return quickSort(arr, 0, arr.length - 1); + } + + private int[] quickSort(int[] arr, int left, int right) { + if (left < right) { + int partitionIndex = partition(arr, left, right); + quickSort(arr, left, partitionIndex - 1); + quickSort(arr, partitionIndex + 1, right); + } + return arr; + } + + private int partition(int[] arr, int left, int right) { + // 设定基准值(pivot) + int pivot = left; + int index = pivot + 1; + for (int i = index; i <= right; i++) { + if (arr[i] < arr[pivot]) { + swap(arr, i, index); + index++; + } + } + swap(arr, pivot, index - 1); + return index - 1; + } + + private void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + +} diff --git a/src/java/main/RadixSort.java b/src/java/main/RadixSort.java new file mode 100644 index 0000000..9052e76 --- /dev/null +++ b/src/java/main/RadixSort.java @@ -0,0 +1,83 @@ +import java.util.Arrays; + +/** + * 基数排序 + *

+ * 考虑负数的情况还可以参考: https://code.i-harness.com/zh-CN/q/e98fa9 + */ +public class RadixSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + int maxDigit = getMaxDigit(arr); + return radixSort(arr, maxDigit); + } + + /** + * 获取最高位数 + */ + private int getMaxDigit(int[] arr) { + int maxValue = getMaxValue(arr); + return getNumLenght(maxValue); + } + + private int getMaxValue(int[] arr) { + int maxValue = arr[0]; + for (int value : arr) { + if (maxValue < value) { + maxValue = value; + } + } + return maxValue; + } + + protected int getNumLenght(long num) { + if (num == 0) { + return 1; + } + int lenght = 0; + for (long temp = num; temp != 0; temp /= 10) { + lenght++; + } + return lenght; + } + + private int[] radixSort(int[] arr, int maxDigit) { + int mod = 10; + int dev = 1; + + for (int i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) { + // 考虑负数的情况,这里扩展一倍队列数,其中 [0-9]对应负数,[10-19]对应正数 (bucket + 10) + int[][] counter = new int[mod * 2][0]; + + for (int j = 0; j < arr.length; j++) { + int bucket = ((arr[j] % mod) / dev) + mod; + counter[bucket] = arrayAppend(counter[bucket], arr[j]); + } + + int pos = 0; + for (int[] bucket : counter) { + for (int value : bucket) { + arr[pos++] = value; + } + } + } + + return arr; + } + + /** + * 自动扩容,并保存数据 + * + * @param arr + * @param value + */ + private int[] arrayAppend(int[] arr, int value) { + arr = Arrays.copyOf(arr, arr.length + 1); + arr[arr.length - 1] = value; + return arr; + } +} diff --git a/src/java/main/SelectionSort.java b/src/java/main/SelectionSort.java new file mode 100644 index 0000000..0cee685 --- /dev/null +++ b/src/java/main/SelectionSort.java @@ -0,0 +1,34 @@ +import java.util.Arrays; + +/** + * 选择排序 + */ +public class SelectionSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + // 总共要经过 N-1 轮比较 + for (int i = 0; i < arr.length - 1; i++) { + int min = i; + + // 每轮需要比较的次数 N-i + for (int j = i + 1; j < arr.length; j++) { + if (arr[j] < arr[min]) { + // 记录目前能找到的最小值元素的下标 + min = j; + } + } + + // 将找到的最小值和i位置所在的值进行交换 + if (i != min) { + int tmp = arr[i]; + arr[i] = arr[min]; + arr[min] = tmp; + } + + } + return arr; + } +} diff --git a/src/java/main/ShellSort.java b/src/java/main/ShellSort.java new file mode 100644 index 0000000..6c0fbb1 --- /dev/null +++ b/src/java/main/ShellSort.java @@ -0,0 +1,33 @@ +import java.util.Arrays; + +/** + * 希尔排序 + */ +public class ShellSort implements IArraySort { + + @Override + public int[] sort(int[] sourceArray) throws Exception { + // 对 arr 进行拷贝,不改变参数内容 + int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); + + int gap = 1; + while (gap < arr.length) { + gap = gap * 3 + 1; + } + + while (gap > 0) { + for (int i = gap; i < arr.length; i++) { + int tmp = arr[i]; + int j = i - gap; + while (j >= 0 && arr[j] > tmp) { + arr[j + gap] = arr[j]; + j -= gap; + } + arr[j + gap] = tmp; + } + gap = (int) Math.floor(gap / 3); + } + + return arr; + } +} diff --git a/src/java/pom.xml b/src/java/pom.xml new file mode 100644 index 0000000..60b4858 --- /dev/null +++ b/src/java/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + + com.corning + sort + 1.0-SNAPSHOT + + + + + CorningSun + corningsun@163.com + http://www.corningsun.com + + + + + + UTF-8 + LATEST + + + + + junit + junit + ${dependency.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.20.1 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/java/target/maven-archiver/pom.properties b/src/java/target/maven-archiver/pom.properties new file mode 100644 index 0000000..5239a24 --- /dev/null +++ b/src/java/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Fri Jan 05 09:51:14 CST 2018 +version=1.0-SNAPSHOT +groupId=com.corning +artifactId=sort diff --git a/src/java/target/sort-1.0-SNAPSHOT.jar b/src/java/target/sort-1.0-SNAPSHOT.jar new file mode 100644 index 0000000..14116be Binary files /dev/null and b/src/java/target/sort-1.0-SNAPSHOT.jar differ diff --git a/src/java/test/ArraySortTest.java b/src/java/test/ArraySortTest.java new file mode 100644 index 0000000..580701f --- /dev/null +++ b/src/java/test/ArraySortTest.java @@ -0,0 +1,142 @@ +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Random; + +import static org.junit.Assert.*; + +/** + * Created by corning on 2017/12/19. + */ +public class ArraySortTest { + + private int[] array; + private int[] sortedArray; + + // 计数排序等不支持负数排序 + private int[] positiveArray; + private int[] positiveArraySorted; + + @Before + public void setUp() throws Exception { + // 生成随机数组 + array = randomArray(-1000, 1000, 100); + // 使用 Arrays.sort() 排序作为对比 + sortedArray = Arrays.copyOf(array, array.length); + Arrays.sort(sortedArray); + + positiveArray = randomArray(0, 1000, 100); + positiveArraySorted = Arrays.copyOf(positiveArray, positiveArray.length); + Arrays.sort(positiveArraySorted); + } + + /** + * 随机指定范围内N个不重复的数 + * 在初始化的无重复待选数组中随机产生一个数放入结果中, + * 将待选数组被随机到的数,用待选数组(len-1)下标对应的数替换 + * 然后从len-2里随机产生下一个随机数,如此类推 + * + * @param max 指定范围最大值 + * @param min 指定范围最小值 + * @param n 随机数个数 + * @return int[] 随机数结果集 + */ + public int[] randomArray(int min, int max, int n) { + int len = max - min + 1; + + if (max < min || n > len) { + return null; + } + + //初始化给定范围的待选数组 + int[] source = new int[len]; + for (int i = min; i < min + len; i++) { + source[i - min] = i; + } + + int[] result = new int[n]; + Random rd = new Random(); + int index = 0; + for (int i = 0; i < result.length; i++) { + //待选数组0到(len-2)随机一个下标 + index = Math.abs(rd.nextInt() % len--); + //将随机到的数放入结果集 + result[i] = source[index]; + //将待选数组中被随机到的数,用待选数组(len-1)下标对应的数替换 + source[index] = source[len]; + } + return result; + } + + @After + public void tearDown() throws Exception { + array = null; + sortedArray = null; + } + + @Test + public void bubbleSort() throws Exception { + assertArrayEquals(sortedArray, new BubbleSort().sort(array)); + } + + @Test + public void choiceSort() throws Exception { + assertArrayEquals(sortedArray, new SelectionSort().sort(array)); + } + + @Test + public void insertSort() throws Exception { + assertArrayEquals(sortedArray, new InsertSort().sort(array)); + } + + @Test + public void shellSort() throws Exception { + assertArrayEquals(sortedArray, new ShellSort().sort(array)); + } + + @Test + public void mergeSort() throws Exception { + assertArrayEquals(sortedArray, new MergeSort().sort(array)); + } + + @Test + public void mergeSort_merge() throws Exception { + assertArrayEquals(new int[]{1, 2}, new MergeSort().merge(new int[]{1, 2}, new int[]{})); + assertArrayEquals(new int[]{1, 2}, new MergeSort().merge(new int[]{1}, new int[]{2})); + assertArrayEquals(new int[]{1, 2, 3}, new MergeSort().merge(new int[]{1, 3}, new int[]{2})); + } + + @Test + public void quickSort() throws Exception { + assertArrayEquals(sortedArray, new QuickSort().sort(array)); + } + + @Test + public void heapSort() throws Exception { + assertArrayEquals(sortedArray, new HeapSort().sort(array)); + } + + @Test + public void countingSort() throws Exception { + assertArrayEquals(positiveArraySorted, new CountingSort().sort(positiveArray)); + } + + @Test + public void bucketSort() throws Exception { + assertArrayEquals(sortedArray, new BucketSort().sort(array)); + } + + @Test + public void radixSort() throws Exception { + assertArrayEquals(sortedArray, new RadixSort().sort(array)); + } + + @Test + public void radixSort_getNumLenght() throws Exception { + assertEquals(3, new RadixSort().getNumLenght(-100)); + assertEquals(1, new RadixSort().getNumLenght(1)); + } + +} \ No newline at end of file diff --git a/src/phpSortTest.php b/src/phpSortTest.php new file mode 100644 index 0000000..4fc59d5 --- /dev/null +++ b/src/phpSortTest.php @@ -0,0 +1,304 @@ + + * + * 主要参考了 JS 的写法及网上的一些写法。 + * + * Require: php -v >= 5.4 + * Test: php phpSortTest.php + */ + +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/src/pythonSortTest.py b/src/pythonSortTest.py index eb5b137..bf092db 100644 --- a/src/pythonSortTest.py +++ b/src/pythonSortTest.py @@ -1,78 +1,90 @@ -''' +''' # Create by LokiSharp(loki.sharp#gmail) at 2017-1-22 ''' -TOTAL=5000 +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))] + arrList = [i for i in range(-math.floor(total / 2), math.ceil(total / 2))] arrListR = copy.deepcopy(arrList) - while operator.eq(arrList,arrListR): + 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)) + # 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)) + 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) + 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) + 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]: + 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] + for i in range(len(arr) - 1): + # 记录最小数的索引 + minIndex = i + for j in range(i + 1, len(arr)): + if arr[j] < arr[minIndex]: + minIndex = j + # i 不是最小数时,将 i 和最小数进行交换 + if i != minIndex: + arr[i], arr[minIndex] = arr[minIndex], arr[i] return arr + def insertionSort(arr): for i in range(len(arr)): - preIndex = i-1 + preIndex = i - 1 current = arr[i] while preIndex >= 0 and arr[preIndex] > current: - arr[preIndex+1] = arr[preIndex] - preIndex-=1 - arr[preIndex+1] = 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 + gap = 1 + while (gap < len(arr) / 3): + gap = gap * 3 + 1 while gap > 0: - for i in range(gap,len(arr)): + 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) + 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): + if (len(arr) < 2): return arr - middle = math.floor(len(arr)/2) + middle = math.floor(len(arr) / 2) left, right = arr[0:middle], arr[middle:] return merge(mergeSort(left), mergeSort(right)) -def merge(left,right): + +def merge(left, right): result = [] while left and right: if left[0] <= right[0]: @@ -85,38 +97,43 @@ def merge(left,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 + 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) + quickSort(arr, left, partitionIndex - 1) + quickSort(arr, partitionIndex + 1, right) return arr + def partition(arr, left, right): pivot = left - index = pivot+1 + index = pivot + 1 i = index - while i <= right: + while i <= right: if arr[i] < arr[pivot]: swap(arr, i, index) - index+=1 - i+=1 - swap(arr,pivot,index-1) - return index-1 + 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) + 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 + left = 2 * i + 1 + right = 2 * i + 2 largest = i if left < arrLen and arr[left] > arr[largest]: largest = left @@ -127,39 +144,73 @@ def heapify(arr, 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 + 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 + 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 + bucket[arr[i]] = 0 + bucket[arr[i]] += 1 for j in range(bucketLen): - while bucket[j]>0: + while bucket[j] > 0: arr[sortedIndex] = j - sortedIndex+=1 - bucket[j]-=1 + 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) +def radix_count(exp1): + global list + n = len(list) + output = [0] * (n) + count = [0] * (10) + for i in range(0, n): + index = (list[i] / exp1) + count[(index) % 10] += 1 + for i in range(1,10): + count[i] += count[i - 1] + i = n - 1 + while i >= 0: + index = (list[i]/exp1) + output[count[(index) % 10] - 1] = list[i] + count[(index) % 10] -= 1 + i -= 1 + i = 0 + for i in range(0,len(list)): + list[i] = output[i] + +def radixSort(): + global list + max1 = max(list) + exp = 1 + while max1 / exp > 0: + radix_count(exp) + exp *= 10 + + +if __name__ == '__main__': + sortTest(bubbleSort, TOTAL) + sortTest(selectionSort, TOTAL) + sortTest(insertionSort, TOTAL) + sortTest(shellSort, TOTAL) + sortTest(mergeSort, TOTAL) + sortTest(quickSort, TOTAL) + sortTest(heapSort, 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)