├── .gitignore ├── src └── main │ └── java │ └── com │ └── example │ ├── Test.java │ ├── Bench.java │ └── SortAlgorithms.java ├── BENCH_RESULT.md ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /src/main/java/com/example/Test.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * 排序算法测试类 7 | */ 8 | public class Test { 9 | private static Bench.Function algorithm = 10 | // Change to Bench.quickSort or Bench.mergeSort as appropriate. 11 | Bench.insertionSort; //直接插入排序 // 需要测试的排序算法 12 | // Bench.shellSort; //希尔排序 13 | // Bench.selectionSort; //简单选择排序 14 | // Bench.heapSort; //堆排序 15 | // Bench.bubbleSort; //冒泡排序 16 | // Bench.quickSort; //快速排序 17 | // Bench.mergeSort; //归并排序 18 | // Bench.radixSort; //基数排序 19 | 20 | 21 | private static boolean check(int[] array) { 22 | int[] reference = Arrays.copyOf(array, array.length); 23 | int[] result; 24 | Arrays.sort(reference); 25 | 26 | try { 27 | result = algorithm.apply(Arrays.copyOf(array, array.length)); 28 | } catch (Exception|StackOverflowError e) { 29 | failed(array, reference); 30 | System.out.println("Threw exception:"); 31 | e.printStackTrace(System.out); 32 | return false; 33 | } 34 | 35 | if (!Arrays.equals(result, reference)) { 36 | failed(array, reference); 37 | System.out.println("Actual answer: " + show(result)); 38 | return false; 39 | } 40 | 41 | return true; 42 | } 43 | 44 | private static void failed(int[] array, int[] reference) { 45 | System.out.println("Failed!"); 46 | System.out.println("Input array: " + show(array)); 47 | System.out.println("Expected answer: " + show(reference)); 48 | } 49 | 50 | private static String show(int[] array) { 51 | StringBuilder result = new StringBuilder(); 52 | result.append("{"); 53 | if (array.length > 0) result.append(array[0]); 54 | for (int i = 1; i < array.length; i++) { 55 | result.append(", "); 56 | result.append(array[i]); 57 | } 58 | result.append("}"); 59 | 60 | return result.toString(); 61 | } 62 | 63 | public static void main(String[] args) { 64 | for (int size = 0; ; size++) { 65 | System.out.printf("Testing on arrays of size %d...\n", size); 66 | int[] sortedSample = Bench.generateSample(size, 0); 67 | int[] partiallySortedSample = Bench.generateSample(size, 5); 68 | int[] randomSample = Bench.generateSample(size, 100); 69 | 70 | if (!check(sortedSample)) return; 71 | if (!check(partiallySortedSample)) return; 72 | if (!check(randomSample)) return; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /BENCH_RESULT.md: -------------------------------------------------------------------------------- 1 | ## 八大排序算法耗时对比 2 | 3 | 当int数组长度分别为 10, 30, 100, 300, 1000, 3000 时,使用排序算法对对应的数组进行排序,耗时结果如下。 4 | 5 | 6 | ### Arrays of length 10 7 | 8 | | Algorithm | Random | 95% sorted | Sorted | 9 | | :------------- | ---------: | ---------: | ---------: | 10 | | Insertion sort | 0.004615ms | 0.000785ms | 0.000023ms | 11 | | Shell sort | 0.007287ms | 0.002860ms | 0.002230ms | 12 | | Selection sort | 0.001599ms | 0.000809ms | 0.000059ms | 13 | | Heap sort | 0.002094ms | 0.002083ms | 0.002085ms | 14 | | Bubble sort | 0.004517ms | 0.000814ms | 0.000063ms | 15 | | Quicksort | 0.001377ms | 0.001586ms | 0.001786ms | 16 | | Merge sort | 0.004518ms | 0.000778ms | 0.000026ms | 17 | | Radix sort | 0.000644ms | 0.000646ms | 0.000645ms | 18 | 19 | ### Arrays of length 30 20 | 21 | | Algorithm | Random | 95% sorted | Sorted | 22 | | :------------- | ---------: | ---------: | ---------: | 23 | | Insertion sort | 0.123324ms | 0.000604ms | 0.000054ms | 24 | | Shell sort | 0.139223ms | 0.026520ms | 0.025894ms | 25 | | Selection sort | 0.015083ms | 0.001262ms | 0.000680ms | 26 | | Heap sort | 0.017556ms | 0.017629ms | 0.018402ms | 27 | | Bubble sort | 0.122594ms | 0.001022ms | 0.000486ms | 28 | | Quicksort | 0.011668ms | 0.015174ms | 0.016193ms | 29 | | Merge sort | 0.123781ms | 0.000607ms | 0.000055ms | 30 | | Radix sort | 0.002077ms | 0.002150ms | 0.002108ms | 31 | 32 | ### Arrays of length 100 33 | 34 | | Algorithm | Random | 95% sorted | Sorted | 35 | | :------------- | ---------: | ---------: | ---------: | 36 | | Insertion sort | 5.751262ms | 0.056025ms | 0.000166ms | 37 | | Shell sort | 5.378896ms | 0.393119ms | 0.337421ms | 38 | | Selection sort | 0.199311ms | 0.064833ms | 0.010262ms | 39 | | Heap sort | 0.203811ms | 0.203682ms | 0.205747ms | 40 | | Bubble sort | 5.898053ms | 0.061130ms | 0.004886ms | 41 | | Quicksort | 0.137751ms | 0.177324ms | 0.191210ms | 42 | | Merge sort | 5.882192ms | 0.056593ms | 0.000167ms | 43 | | Radix sort | 0.006145ms | 0.006067ms | 0.006044ms | 44 | 45 | ### Arrays of length 300 46 | 47 | | Algorithm | Random | 95% sorted | Sorted | 48 | | :------------- | -----------: | ----------: | ---------: | 49 | | Insertion sort | 142.971101ms | 12.366163ms | 0.000506ms | 50 | | Shell sort | 105.500973ms | 13.471134ms | 4.468945ms | 51 | | Selection sort | 2.007829ms | 1.323869ms | 0.107584ms | 52 | | Heap sort | 2.159838ms | 2.144288ms | 2.174938ms | 53 | | Bubble sort | 142.216001ms | 12.115499ms | 0.040407ms | 54 | | Quicksort | 1.330195ms | 1.654192ms | 1.971377ms | 55 | | Merge sort | 144.561227ms | 12.521661ms | 0.000508ms | 56 | | Radix sort | 0.029518ms | 0.028453ms | 0.028831ms | 57 | 58 | ### Arrays of length 1000 59 | 60 | | Algorithm | Random | 95% sorted | Sorted | 61 | | :------------- | ------------: | -----------: | ----------: | 62 | | Insertion sort | 5649.939294ms | 360.765524ms | 0.001362ms | 63 | | Shell sort | 4399.805254ms | 310.691632ms | 43.263064ms | 64 | | Selection sort | 23.631708ms | 22.496570ms | 1.237903ms | 65 | | Heap sort | 23.676803ms | 23.326309ms | 23.421163ms | 66 | | Bubble sort | 5807.787855ms | 363.755447ms | 0.438336ms | 67 | | Quicksort | 15.424505ms | 16.081330ms | 22.285714ms | 68 | | Merge sort | 5822.908516ms | 355.370353ms | 0.001390ms | 69 | | Radix sort | 0.097762ms | 0.097361ms | 0.126791ms | 70 | 71 | ### Arrays of length 3000 72 | 73 | | Algorithm | Random | 95% sorted | Sorted | 74 | | :------------- | --------------: | -------------: | -----------: | 75 | | Insertion sort | 171271.760752ms | 11119.063850ms | 0.004004ms | 76 | | Shell sort | 116029.883053ms | 8348.448500ms | 502.211498ms | 77 | | Selection sort | 229.224797ms | 203.127196ms | 11.105693ms | 78 | | Heap sort | 235.891323ms | 230.794397ms | 228.503595ms | 79 | | Bubble sort | 177897.584737ms | 11223.376504ms | 3.845661ms | 80 | | Quicksort | 151.487124ms | 162.464997ms | 217.498977ms | 81 | | Merge sort | 171893.042008ms | 11281.756808ms | 0.004078ms | 82 | | Radix sort | 0.427945ms | 0.416584ms | 0.417483ms | 83 | -------------------------------------------------------------------------------- /src/main/java/com/example/Bench.java: -------------------------------------------------------------------------------- 1 | package com.example;// 2 | // HERE BE DRAGONS! 3 | // 4 | // You don't have to read any of this file. 5 | // It's just the benchmarking program. 6 | // 7 | 8 | import java.util.*; 9 | 10 | /** 11 | * 排序算法分析评价类,比较各算法耗时 12 | * 参考 http://www.cse.chalmers.se/edu/course/DIT960/lab1-sorting.html 13 | */ 14 | public class Bench { 15 | /** Main function **/ 16 | 17 | public static void main(final String[] args) { 18 | executionTimeReport(); 19 | } 20 | 21 | /** Test data generator **/ 22 | 23 | // Generates a random array of size 'size'. 24 | // Part of the array is sorted, while the rest is chosen uniformly 25 | // at random; the 'randomness' parameter sets what percent of the 26 | // array is chosen at random. 27 | public static int[] generateSample(int size, int randomness) { 28 | int[] sample = new int[size]; 29 | 30 | Random random = new Random(); 31 | int previousElement = 0; 32 | for (int i = 0; i < size; i++) { 33 | if (random.nextInt(100) >= randomness) { 34 | int randomOffset = random.nextInt(3); 35 | int currentElement = previousElement + randomOffset; 36 | sample[i] = currentElement; 37 | previousElement = currentElement; 38 | } else { 39 | sample[i] = random.nextInt(size); 40 | } 41 | } 42 | 43 | return sample; 44 | } 45 | 46 | /** Auxiliary code, that measures performance of sorting algorithms **/ 47 | 48 | private static int[] SAMPLE_SIZES = new int[] { 10, 30, 100, 300, 1000, 3000, 10000, 30000, 100000 }; 49 | private static void executionTimeReport() { 50 | for (int size : SAMPLE_SIZES) { 51 | executionTimeReport(size); 52 | } 53 | } 54 | 55 | public static interface Function { 56 | public B apply(A arg); 57 | } 58 | 59 | public static Function insertionSort = new Function() { 60 | @Override public int[] apply(int[] array) { 61 | SortAlgorithms.insertionSort(array); 62 | return array; 63 | } 64 | }; 65 | 66 | public static Function shellSort = new Function() { 67 | @Override public int[] apply(int[] array) { 68 | SortAlgorithms.shellSort(array); 69 | return array; 70 | } 71 | }; 72 | 73 | public static Function selectionSort = new Function() { 74 | @Override public int[] apply(int[] array) { 75 | SortAlgorithms.selectionSort(array); 76 | return array; 77 | } 78 | }; 79 | 80 | public static Function heapSort = new Function() { 81 | @Override public int[] apply(int[] array) { 82 | SortAlgorithms.heapSort(array); 83 | return array; 84 | } 85 | }; 86 | 87 | public static Function bubbleSort = new Function() { 88 | @Override public int[] apply(int[] array) { 89 | SortAlgorithms.bubbleSort(array); 90 | return array; 91 | } 92 | }; 93 | 94 | 95 | public static Function quickSort = new Function() { 96 | @Override public int[] apply(int[] array) { 97 | SortAlgorithms.quickSort(array, 0, array.length-1); 98 | return array; 99 | } 100 | }; 101 | 102 | public static Function mergeSort = new Function() { 103 | @Override public int[] apply(int[] array) { 104 | SortAlgorithms.insertionSort(array); 105 | return array; 106 | } 107 | }; 108 | 109 | public static Function radixSort = new Function() { 110 | @Override public int[] apply(int[] array) { 111 | SortAlgorithms.radixSort(array); 112 | return array; 113 | } 114 | }; 115 | 116 | // Execute an algorithm on an input and return its runtime. 117 | private static String execute(Function algorithm, int[] input) { 118 | // To get accurate results even for small inputs, we repeat 119 | // the algorithm several times in a row and count the total time. 120 | // We pick the number of repetitions automatically so that 121 | // the total time is at least 10ms. 122 | // 123 | // To pick the number of repetitions, we start by assuming 124 | // that one repetition will be enough. We then execute the 125 | // algorithm and measure how long it takes. If it took less 126 | // than 10ms, we scale up the number of repetitions by 127 | // an appropriate factor. E.g., if the algorithm only took 128 | // 1ms, we will multiply the number of repetitions by 10. 129 | // We then repeat this whole process with the new number of 130 | // repetitions. 131 | // 132 | // Once the repetitions take more than 10ms, we try it three 133 | // times and take the smallest measured runtime. This avoids 134 | // freakish results due to e.g. the garbage collector kicking 135 | // in at the wrong time. 136 | 137 | // Minimum acceptable value for total time. 138 | final long target = 10000000; 139 | // How many times to re-measure the algorithm once it hits the 140 | // target time. 141 | final int MAX_LIVES = 3; 142 | // The final result of the algorithm. 143 | int[] result = {}; 144 | // How many repetitions we guess will be enough. 145 | int repetitions = 1; 146 | // The lowest runtime we saw with the current number of repetitions. 147 | long runtime = Long.MAX_VALUE; 148 | // How many times we've measured after hitting the target time. 149 | int lives = MAX_LIVES; 150 | try { 151 | while(true) { 152 | // Build the input arrays in advance to avoid memory 153 | // allocation during testing. 154 | int[][] inputs = new int[repetitions][]; 155 | for (int i = 0; i < repetitions; i++) 156 | inputs[i] = Arrays.copyOf(input, input.length); 157 | // Try to reduce unpredictability 158 | System.gc(); 159 | Thread.yield(); 160 | 161 | // Run the algorithm 162 | long startTime = System.nanoTime(); 163 | for (int i = 0; i < repetitions; i++) 164 | result = algorithm.apply(inputs[i]); 165 | long endTime = System.nanoTime(); 166 | runtime = Math.min(runtime, endTime - startTime); 167 | 168 | // If the algorithm is really slow, we don't 169 | // need to measure too carefully 170 | if (repetitions == 1 && runtime >= 30*target) 171 | break; 172 | if (runtime >= target) { 173 | // Ran for long enough - reduce number of lives by one. 174 | if (lives == 0) break; else lives--; 175 | } else { 176 | // Didn't run for long enough. 177 | // Increase number of repetitions to try to hit 178 | // target - but at least double it. 179 | if (runtime == 0) 180 | repetitions *= 2; 181 | else 182 | repetitions *= 2 * target / runtime; 183 | runtime = Long.MAX_VALUE; 184 | lives = MAX_LIVES; 185 | } 186 | } 187 | } catch (UnsupportedOperationException uop) { 188 | return "-"; 189 | } catch (Exception e) { 190 | return "EXCEPTION"; 191 | } catch (StackOverflowError e) { 192 | return "STACK OVERFLOW"; 193 | } 194 | int[] reference = Arrays.copyOf(input, input.length); 195 | Arrays.sort(reference); 196 | if (Arrays.equals(result, reference)) { 197 | return String.format("%6f", (double)runtime / ((long)repetitions * 1000000)) + "ms"; 198 | } else { 199 | return "INCORRECT"; 200 | } 201 | } 202 | 203 | private static void executionTimeReport(int size) { 204 | int[] sortedSample = generateSample(size, 0); 205 | int[] partiallySortedSample = generateSample(size, 5); 206 | int[] randomSample = generateSample(size, 100); 207 | 208 | System.out.println(String.format( 209 | "### Arrays of length %d\n" + 210 | "=================================================================\n" + 211 | "| Algorithm | %14s | %14s | %14s |\n" + 212 | "| %3s | %14s | %14s | %14s |\n" + 213 | "| Insertion sort | %14s | %14s | %14s |\n" + 214 | "| Shell sort | %14s | %14s | %14s |\n" + 215 | "| Selection sort | %14s | %14s | %14s |\n" + 216 | "| Heap sort | %14s | %14s | %14s |\n" + 217 | "| Bubble sort | %14s | %14s | %14s |\n" + 218 | "| Quicksort | %14s | %14s | %14s |\n" + 219 | "| Merge sort | %14s | %14s | %14s |\n" + 220 | "| Radix sort | %14s | %14s | %14s |\n", 221 | size, 222 | "Random", "95% sorted", "Sorted", 223 | ":--", "---:", "---:", "---:", 224 | execute(insertionSort, randomSample), 225 | execute(insertionSort, partiallySortedSample), 226 | execute(insertionSort, sortedSample), 227 | 228 | execute(shellSort, randomSample), 229 | execute(shellSort, partiallySortedSample), 230 | execute(shellSort, sortedSample), 231 | 232 | execute(selectionSort, randomSample), 233 | execute(selectionSort, partiallySortedSample), 234 | execute(selectionSort, sortedSample), 235 | 236 | execute(heapSort, randomSample), 237 | execute(heapSort, partiallySortedSample), 238 | execute(heapSort, sortedSample), 239 | 240 | execute(bubbleSort, randomSample), 241 | execute(bubbleSort, partiallySortedSample), 242 | execute(bubbleSort, sortedSample), 243 | 244 | execute(quickSort, randomSample), 245 | execute(quickSort, partiallySortedSample), 246 | execute(quickSort, sortedSample), 247 | 248 | execute(mergeSort, randomSample), 249 | execute(mergeSort, partiallySortedSample), 250 | execute(mergeSort, sortedSample), 251 | 252 | execute(radixSort, randomSample), 253 | execute(radixSort, partiallySortedSample), 254 | execute(radixSort, sortedSample) 255 | )); 256 | } 257 | } 258 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2017] [iTimeTraveler] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/main/java/com/example/SortAlgorithms.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | /** 7 | * 八大排序算法实现 8 | * 9 | * 1. 直接插入排序 {@link #insertionSort} 10 | * 2. 希尔排序 {@link #shellSort} 11 | * 3. 简单选择排序 {@link #selectionSort} 12 | * 4. 堆排序 {@link #heapSort} 13 | * 5. 冒泡排序 {@link #bubbleSort} 14 | * 6. 快速排序 {@link #quickSort} 15 | * 7. 归并排序 {@link #mergingSort} 16 | * 8. 基数排序 {@link #radixSort} 17 | * 18 | * 算法测试类见 {@link Test} 19 | * 算法评估分析类见 {@link Bench} 20 | * 21 | */ 22 | public class SortAlgorithms { 23 | public static final boolean ENABLE_PRINT = false; 24 | 25 | public static void main(String[] args) { 26 | // int[] array = new int[]{3,5,3,0,8,6,1,5,8,6,2,4,9,4,7,0,1,8,9,7,3,1,2,5,9,7,4,0,2,6}; 27 | int[] array = new int[]{5, 3, 9, 1, 6, 4, 10, 2, 8, 7, 15, 3, 2}; 28 | // int[] array = new int[]{1, 1, 0}; 29 | 30 | System.out.println("Before: " + Arrays.toString(array)); 31 | SortAlgorithms.insertionSort(array); 32 | // SortAlgorithms.shellSort(array); 33 | // SortAlgorithms.selectionSort(array); 34 | // SortAlgorithms.heapSort(array); 35 | // SortAlgorithms.bubbleSort(array); 36 | // SortAlgorithms.quickSort(array, 0, array.length-1); 37 | // SortAlgorithms.quickSortByStack(array); 38 | // array = SortAlgorithms.mergingSort(array); 39 | // SortAlgorithms.radixSort(array); 40 | System.out.println("After: " + Arrays.toString(array)); 41 | } 42 | 43 | 44 | /** 45 | * 统一控制是否控制台输出 46 | */ 47 | private static void System_out_println(String str){ 48 | if(ENABLE_PRINT){ 49 | System.out.println(str); 50 | } 51 | } 52 | 53 | /** 54 | * 直接插入排序 55 | * 56 | * 1. 从第一个元素开始,该元素可以认为已经被排序 57 | * 2. 取出下一个元素,在已经排序的元素序列中从后向前扫描 58 | * 3. 如果该元素(已排序)大于新元素,将该元素移到下一位置 59 | * 4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置 60 | * 5. 将新元素插入到该位置后 61 | * 6. 重复步骤2~5 62 | * @param arr 待排序数组 63 | */ 64 | public static void insertionSort(int[] arr){ 65 | for( int i=0; i0; j-- ) { 67 | if( arr[j-1] <= arr[j] ) 68 | break; 69 | int temp = arr[j]; //交换操作 70 | arr[j] = arr[j-1]; 71 | arr[j-1] = temp; 72 | System_out_println("Sorting: " + Arrays.toString(arr)); 73 | } 74 | } 75 | } 76 | 77 | 78 | /** 79 | * 希尔排序 80 | * 81 | * 1. 选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;(一般初次取数组半长,之后每次再减半,直到增量为1) 82 | * 2. 按增量序列个数k,对序列进行k 趟排序; 83 | * 3. 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。 84 | * 仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 85 | * @param arr 待排序数组 86 | */ 87 | public static void shellSort(int[] arr){ 88 | int gap = arr.length / 2; 89 | for (; gap > 0; gap /= 2) { //不断缩小gap,直到1为止 90 | System_out_println("Gap=" + gap); 91 | for (int j = 0; (j+gap) < arr.length; j++){ //使用当前gap进行组内插入排序 92 | for(int k = 0; (k+gap)< arr.length; k += gap){ 93 | System_out_println("Compare: arr[" + (k+gap)+ "]=" + arr[k+gap] + ", arr[" + k + "]=" + arr[k]); 94 | if(arr[k] > arr[k+gap]) { 95 | int temp = arr[k+gap]; //交换操作 96 | arr[k+gap] = arr[k]; 97 | arr[k] = temp; 98 | System_out_println(" Sorting: " + Arrays.toString(arr)); 99 | } 100 | } 101 | } 102 | } 103 | } 104 | 105 | /** 106 | * 希尔排序(Wiki官方版) 107 | * 108 | * 1. 选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;(注意此算法的gap取值) 109 | * 2. 按增量序列个数k,对序列进行k 趟排序; 110 | * 3. 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。 111 | * 仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 112 | * @param arr 待排序数组 113 | */ 114 | public static void shell_sort(int[] arr) { 115 | int gap = 1, i, j, len = arr.length; 116 | int temp; 117 | while (gap < len / 3) 118 | gap = gap * 3 + 1; // : 1, 4, 13, 40, 121, ... 119 | for (; gap > 0; gap /= 3) { 120 | for (i = gap; i < len; i++) { 121 | temp = arr[i]; 122 | for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap) 123 | arr[j + gap] = arr[j]; 124 | arr[j + gap] = temp; 125 | } 126 | } 127 | } 128 | 129 | /** 130 | * 选择排序 131 | * 132 | * 1. 从待排序序列中,找到关键字最小的元素; 133 | * 2. 如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换; 134 | * 3. 从余下的 N - 1 个元素中,找出关键字最小的元素,重复①、②步,直到排序结束。 135 | * 仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 136 | * @param arr 待排序数组 137 | */ 138 | public static void selectionSort(int[] arr){ 139 | for(int i = 0; i < arr.length-1; i++){ 140 | int min = i; 141 | for(int j = i+1; j < arr.length; j++){ //选出之后待排序中值最小的位置 142 | if(arr[j] < arr[min]){ 143 | min = j; 144 | } 145 | } 146 | if(min != i){ 147 | int temp = arr[min]; //交换操作 148 | arr[min] = arr[i]; 149 | arr[i] = temp; 150 | System_out_println("Sorting: " + Arrays.toString(arr)); 151 | } 152 | } 153 | } 154 | 155 | 156 | /** 157 | * 堆排序 158 | * 159 | * 1. 先将初始序列K[1..n]建成一个大顶堆, 那么此时第一个元素K1最大, 此堆为初始的无序区. 160 | * 2. 再将关键字最大的记录K1 (即堆顶, 第一个元素)和无序区的最后一个记录 Kn 交换, 由此得到新的无序区K[1..n−1]和有序区K[n], 且满足K[1..n−1].keys⩽K[n].key 161 | * 3. 交换K1 和 Kn 后, 堆顶可能违反堆性质, 因此需将K[1..n−1]调整为堆. 然后重复步骤②, 直到无序区只有一个元素时停止. 162 | * @param arr 待排序数组 163 | */ 164 | public static void heapSort(int[] arr){ 165 | for(int i = arr.length; i > 0; i--){ 166 | max_heapify(arr, i); 167 | 168 | int temp = arr[0]; //堆顶元素(第一个元素)与Kn交换 169 | arr[0] = arr[i-1]; 170 | arr[i-1] = temp; 171 | } 172 | } 173 | 174 | private static void max_heapify(int[] arr, int limit){ 175 | if(arr.length <= 0 || arr.length < limit) return; 176 | int parentIdx = limit / 2; 177 | 178 | for(; parentIdx >= 0; parentIdx--){ 179 | if(parentIdx * 2 >= limit){ 180 | continue; 181 | } 182 | int left = parentIdx * 2; //左子节点位置 183 | int right = (left + 1) >= limit ? left : (left + 1); //右子节点位置,如果没有右节点,默认为左节点位置 184 | 185 | int maxChildId = arr[left] >= arr[right] ? left : right; 186 | if(arr[maxChildId] > arr[parentIdx]){ //交换父节点与左右子节点中的最大值 187 | int temp = arr[parentIdx]; 188 | arr[parentIdx] = arr[maxChildId]; 189 | arr[maxChildId] = temp; 190 | } 191 | } 192 | System_out_println("Max_Heapify: " + Arrays.toString(arr)); 193 | } 194 | 195 | 196 | /** 197 | * 冒泡排序 198 | * 199 | * ①. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 200 | * ②. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。 201 | * ③. 针对所有的元素重复以上的步骤,除了最后一个。 202 | * ④. 持续每次对越来越少的元素重复上面的步骤①~③,直到没有任何一对数字需要比较。 203 | * @param arr 待排序数组 204 | */ 205 | public static void bubbleSort(int[] arr){ 206 | for (int i = arr.length - 1; i > 0; i--) { //外层循环移动游标 207 | for(int j = 0; j < i; j++){ //内层循环遍历游标及之后(或之前)的元素 208 | if(arr[j] > arr[j+1]){ 209 | int temp = arr[j]; 210 | arr[j] = arr[j+1]; 211 | arr[j+1] = temp; 212 | System_out_println("Sorting: " + Arrays.toString(arr)); 213 | } 214 | } 215 | } 216 | } 217 | 218 | /** 219 | * 快速排序(递归) 220 | * 221 | * ①. 从数列中挑出一个元素,称为"基准"(pivot)。 222 | * ②. 重新排序数列,所有比基准值小的元素摆放在基准前面,所有比基准值大的元素摆在基准后面(相同的数可以到任一边)。在这个分区结束之后,该基准就处于数列的中间位置。这个称为分区(partition)操作。 223 | * ③. 递归地(recursively)把小于基准值元素的子数列和大于基准值元素的子数列排序。 224 | * @param arr 待排序数组 225 | * @param low 左边界 226 | * @param high 右边界 227 | */ 228 | public static void quickSort(int[] arr, int low, int high){ 229 | if(arr.length <= 0) return; 230 | if(low >= high) return; 231 | int left = low; 232 | int right = high; 233 | 234 | int temp = arr[left]; //挖坑1:保存基准的值 235 | while (left < right){ 236 | while(left < right && arr[right] >= temp){ //坑2:从后向前找到比基准小的元素,插入到基准位置坑1中 237 | right--; 238 | } 239 | arr[left] = arr[right]; 240 | while(left < right && arr[left] <= temp){ //坑3:从前往后找到比基准大的元素,放到刚才挖的坑2中 241 | left++; 242 | } 243 | arr[right] = arr[left]; 244 | } 245 | arr[left] = temp; //基准值填补到坑3中,准备分治递归快排 246 | System_out_println("Sorting: " + Arrays.toString(arr)); 247 | quickSort(arr, low, left-1); 248 | quickSort(arr, left+1, high); 249 | } 250 | 251 | 252 | /** 253 | * 快速排序(非递归) 254 | * 255 | * ①. 从数列中挑出一个元素,称为"基准"(pivot)。 256 | * ②. 重新排序数列,所有比基准值小的元素摆放在基准前面,所有比基准值大的元素摆在基准后面(相同的数可以到任一边)。在这个分区结束之后,该基准就处于数列的中间位置。这个称为分区(partition)操作。 257 | * ③. 把分区之后两个区间的边界(low和high)压入栈保存,并循环①、②步骤 258 | * @param arr 待排序数组 259 | */ 260 | public static void quickSortByStack(int[] arr){ 261 | if(arr.length <= 0) return; 262 | Stack stack = new Stack(); 263 | 264 | //初始状态的左右指针入栈 265 | stack.push(0); 266 | stack.push(arr.length - 1); 267 | while(!stack.isEmpty()){ 268 | int high = stack.pop(); //出栈进行划分 269 | int low = stack.pop(); 270 | 271 | int pivotIdx = partition(arr, low, high); 272 | 273 | //保存中间变量 274 | if(pivotIdx > low) { 275 | stack.push(low); 276 | stack.push(pivotIdx - 1); 277 | } 278 | if(pivotIdx < high && pivotIdx >= 0){ 279 | stack.push(pivotIdx + 1); 280 | stack.push(high); 281 | } 282 | } 283 | } 284 | 285 | private static int partition(int[] arr, int low, int high){ 286 | if(arr.length <= 0) return -1; 287 | if(low >= high) return -1; 288 | int l = low; 289 | int r = high; 290 | 291 | int pivot = arr[l]; //挖坑1:保存基准的值 292 | while(l < r){ 293 | while(l < r && arr[r] >= pivot){ //坑2:从后向前找到比基准小的元素,插入到基准位置坑1中 294 | r--; 295 | } 296 | arr[l] = arr[r]; 297 | while(l < r && arr[l] <= pivot){ //坑3:从前往后找到比基准大的元素,放到刚才挖的坑2中 298 | l++; 299 | } 300 | arr[r] = arr[l]; 301 | } 302 | arr[l] = pivot; //基准值填补到坑3中,准备分治递归快排 303 | return l; 304 | } 305 | 306 | 307 | /** 308 | * 归并排序(递归) 309 | * 310 | * ①. 将序列每相邻两个数字进行归并操作,形成 floor(n/2)个序列,排序后每个序列包含两个元素; 311 | * ②. 将上述序列再次归并,形成 floor(n/4)个序列,每个序列包含四个元素; 312 | * ③. 重复步骤②,直到所有元素排序完毕。 313 | * @param arr 待排序数组 314 | */ 315 | public static int[] mergingSort(int[] arr){ 316 | if(arr.length <= 1) return arr; 317 | 318 | int num = arr.length >> 1; 319 | int[] leftArr = Arrays.copyOfRange(arr, 0, num); 320 | int[] rightArr = Arrays.copyOfRange(arr, num, arr.length); 321 | System_out_println("split two array: " + Arrays.toString(leftArr) + " And " + Arrays.toString(rightArr)); 322 | return mergeTwoArray(mergingSort(leftArr), mergingSort(rightArr)); //不断拆分为最小单元,再排序合并 323 | } 324 | 325 | private static int[] mergeTwoArray(int[] arr1, int[] arr2){ 326 | int i = 0, j = 0, k = 0; 327 | int[] result = new int[arr1.length + arr2.length]; //申请额外的空间存储合并之后的数组 328 | while(i < arr1.length && j < arr2.length){ //选取两个序列中的较小值放入新数组 329 | if(arr1[i] <= arr2[j]){ 330 | result[k++] = arr1[i++]; 331 | }else{ 332 | result[k++] = arr2[j++]; 333 | } 334 | } 335 | while(i < arr1.length){ //序列1中多余的元素移入新数组 336 | result[k++] = arr1[i++]; 337 | } 338 | while(j < arr2.length){ //序列2中多余的元素移入新数组 339 | result[k++] = arr2[j++]; 340 | } 341 | System_out_println("Merging: " + Arrays.toString(result)); 342 | return result; 343 | } 344 | 345 | 346 | /** 347 | * 基数排序(LSD 从低位开始) 348 | * 349 | * 基数排序适用于: 350 | * (1)数据范围较小,建议在小于1000 351 | * (2)每个数值都要大于等于0 352 | * 353 | * ①. 取得数组中的最大数,并取得位数; 354 | * ②. arr为原始数组,从最低位开始取每个位组成radix数组; 355 | * ③. 对radix进行计数排序(利用计数排序适用于小范围数的特点); 356 | * @param arr 待排序数组 357 | */ 358 | public static void radixSort(int[] arr){ 359 | if(arr.length <= 1) return; 360 | 361 | //取得数组中的最大数,并取得位数 362 | int max = 0; 363 | for(int i = 0; i < arr.length; i++){ 364 | if(max < arr[i]){ 365 | max = arr[i]; 366 | } 367 | } 368 | int maxDigit = 1; 369 | while(max / 10 > 0){ 370 | maxDigit++; 371 | max = max / 10; 372 | } 373 | System_out_println("maxDigit: " + maxDigit); 374 | 375 | //申请一个桶空间 376 | int[][] buckets = new int[10][arr.length]; 377 | int base = 10; 378 | 379 | //从低位到高位,对每一位遍历,将所有元素分配到桶中 380 | for(int i = 0; i < maxDigit; i++){ 381 | int[] bktLen = new int[10]; //存储各个桶中存储元素的数量 382 | 383 | //分配:将所有元素分配到桶中 384 | for(int j = 0; j < arr.length; j++){ 385 | int whichBucket = (arr[j] % base) / (base / 10); 386 | buckets[whichBucket][bktLen[whichBucket]] = arr[j]; 387 | bktLen[whichBucket]++; 388 | } 389 | 390 | //收集:将不同桶里数据挨个捞出来,为下一轮高位排序做准备,由于靠近桶底的元素排名靠前,因此从桶底先捞 391 | int k = 0; 392 | for(int b = 0; b < buckets.length; b++){ 393 | for(int p = 0; p < bktLen[b]; p++){ 394 | arr[k++] = buckets[b][p]; 395 | } 396 | } 397 | 398 | System_out_println("Sorting: " + Arrays.toString(arr)); 399 | base *= 10; 400 | } 401 | } 402 | } 403 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SortAlgorithms 2 | 3 | 4 | > 原文链接: [**八大排序算法总结与java实现** - iTimeTraveler](https://itimetraveler.github.io/2017/07/18/%E5%85%AB%E5%A4%A7%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95%E6%80%BB%E7%BB%93%E4%B8%8Ejava%E5%AE%9E%E7%8E%B0/) 5 | 6 | 7 | ### 概述 8 | 9 | 因为健忘,加上对各种排序算法理解不深刻,过段时间面对排序就蒙了。所以决定对我们常见的这几种排序算法进行统一总结,强行学习。首先罗列一下常见的十大排序算法: 10 | 11 | ![](https://itimetraveler.github.io/gallery/sort-algorithms/big-o.png) 12 | 13 | 14 | 15 | - [直接插入排序](#一直接插入排序insertion-sort) 16 | - [希尔排序](#二希尔排序shell-sort) 17 | - [简单选择排序](#三选择排序selection-sort) 18 | - [堆排序](#四堆排序heap-sort) 19 | - [冒泡排序](#五冒泡排序bubble-sort) 20 | - [快速排序](#六快速排序quick-sort) 21 | - [归并排序](#七归并排序merging-sort) 22 | - [基数排序](#八基数排序radix-sort) 23 | 24 | 25 | 26 | 其中我们讨论的这八大排序算法的实现可以参考[我的Github:**SortAlgorithms**](https://github.com/iTimeTraveler/SortAlgorithms),其中包括了排序测试模块[[Test.java]](https://github.com/iTimeTraveler/SortAlgorithms/blob/master/src/main/java/com/example/Test.java)和排序算法对比模块[[Bench.java]](https://github.com/iTimeTraveler/SortAlgorithms/blob/master/src/main/java/com/example/Bench.java),大家可以试运行。 27 | 28 | 它们都属于内部排序,也就是只考虑数据量较小仅需要使用内存的排序算法,他们之间关系如下: 29 | 30 | 31 | 32 | ![](https://itimetraveler.github.io/gallery/sort-algorithms/1156494-ab4cecff133d87b3.png) 33 | 34 | 35 | 36 | 37 | 38 | ### 一、直接插入排序(Insertion Sort) 39 | 40 | --- 41 | 42 | 插入排序的设计初衷是**往有序的数组中快速插入一个新的元素**。它的算法思想是:把要排序的数组分为了两个部分, 一部分是数组的全部元素(除去待插入的元素), 另一部分是待插入的元素; 先将第一部分排序完成, 然后再插入这个元素. 其中第一部分的排序也是通过再次拆分为两部分来进行的. 43 | 44 | 插入排序由于操作不尽相同, 可分为 `直接插入排序` , `折半插入排序`(又称二分插入排序), `链表插入排序` , `希尔排序` 。我们先来看下直接插入排序。 45 | 46 | #### 1、基本思想 47 | 48 | 直接插入排序的基本思想是:将数组中的所有元素依次跟前面已经排好的元素相比较,如果选择的元素比已排序的元素小,则交换,直到全部元素都比较过为止。 49 | 50 | ![使用插入排序为一列数字进行排序的过程](https://itimetraveler.github.io/gallery/sort-algorithms/Insertion-sort-example-300px.gif) 51 | 52 | #### 2、算法描述 53 | 54 | 一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下: 55 | 56 | ①. 从第一个元素开始,该元素可以认为已经被排序
57 | ②. 取出下一个元素,在已经排序的元素序列中从后向前扫描
58 | ③. 如果该元素(已排序)大于新元素,将该元素移到下一位置
59 | ④. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
60 | ⑤. 将新元素插入到该位置后
61 | ⑥. 重复步骤②~⑤
62 | 63 | ![直接插入排序演示](https://itimetraveler.github.io/gallery/sort-algorithms/insert-sort.gif) 64 | 65 | 算法实现中比较有意思的一点是,在每次比较操作发现取出来的新元素小于等于已排序的元素时,可以将已排序的元素移到下一位置,然后将取出来的新元素插入该位置(即相邻位置对调),接着再与前面的已排序的元素进行比较,如上图所示,这样做缺点是交换操作代价比较大。另一种做法是:将新元素取出(挖坑),从左到右依次与已排序的元素比较,如果已排序的元素大于取出的新元素,那么将该元素移动到下一个位置(填坑),接着再与前面的已排序的元素比较,直到找到已排序的元素小于等于新元素的位置,这时再将新元素插入进去。就像基本思想中的动图演示的那样。 66 | 67 | 如果*比较操作*的代价比*交换操作*大的话,可以采用[二分查找法](https://zh.wikipedia.org/wiki/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%B3%95)来减少*比较操作*的数目。可以认为是**插入排序**的一个变种,称为[二分查找插入排序](https://zh.wikipedia.org/w/index.php?title=%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F&action=edit&redlink=1)。 68 | 69 | #### 3、代码实现 70 | 71 | ```java 72 | /** 73 | * 插入排序 74 | * 75 | * 1. 从第一个元素开始,该元素可以认为已经被排序 76 | * 2. 取出下一个元素,在已经排序的元素序列中从后向前扫描 77 | * 3. 如果该元素(已排序)大于新元素,将该元素移到下一位置 78 | * 4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置 79 | * 5. 将新元素插入到该位置后 80 | * 6. 重复步骤2~5 81 | * @param arr 待排序数组 82 | */ 83 | public static void insertionSort(int[] arr){ 84 | for( int i = 1; i < arr.length; i++ ) { 85 | int temp = arr[i]; // 取出下一个元素,在已经排序的元素序列中从后向前扫描 86 | for( int j = i; j >= 0; j-- ) { 87 | if( j > 0 && arr[j-1] > temp ) { 88 | arr[j] = arr[j-1]; // 如果该元素(已排序)大于取出的元素temp,将该元素移到下一位置 89 | System.out.println("Temping: " + Arrays.toString(arr)); 90 | } else { 91 | // 将新元素插入到该位置后 92 | arr[j] = temp; 93 | System.out.println("Sorting: " + Arrays.toString(arr)); 94 | break; 95 | } 96 | } 97 | } 98 | } 99 | 100 | // 交换次数较多的实现 101 | public static void insertionSort(int[] arr){ 102 | for( int i=0; i0; j-- ) { 104 | if( arr[j-1] <= arr[j] ) 105 | break; 106 | int temp = arr[j]; //交换操作 107 | arr[j] = arr[j-1]; 108 | arr[j-1] = temp; 109 | System.out.println("Sorting: " + Arrays.toString(arr)); 110 | } 111 | } 112 | } 113 | ``` 114 | 115 | 直接插入排序复杂度如下: 116 | 117 | - 最好情况下,排序前对象已经按照要求的有序。比较次数(KCN):n−1;移动次数(RMN)为0。则对应的时间复杂度为O(n)。 118 | - 最坏情况下,排序前对象为要求的顺序的反序。第i趟时第i个对象必须与前面i个对象都做排序码比较,并且每做1次比较就要做1次数据移动(从上面给出的代码中看出)。比较次数(KCN):n²/2 ; 移动次数(RMN)为:n²/2。则对应的时间复杂度为O(n²)。 119 | - 如果排序记录是随机的,那么根据概率相同的原则,在平均情况下的排序码比较次数和对象移动次数约为n²/2,因此,**直接插入排序的平均时间复杂度**为O(n²)。 120 | 121 | 122 | | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 123 | | ------- | ----- | ----- | ----- | 124 | | O(n²) | O(n) | O(n²) | O(1) | 125 | 126 | Tips: 由于直接插入排序每次只移动一个元素的位, 并不会改变值相同的元素之间的排序, 因此它是一种稳定排序。 127 | 128 | 129 | 130 | 131 | ### 二、希尔排序(Shell Sort) 132 | 133 | --- 134 | 135 | > 第一个突破O(n^2)的排序算法;是简单插入排序的改进版;它与插入排序的不同之处在于,它会优先比较距离较远的元素。 136 | 137 | 138 | 希尔排序,也称**递减增量排序算法**,1959年Shell发明。是插入排序的一种高速而稳定的改进版本。 139 | 140 | 希尔排序是先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录“基本有序”时,再对全体记录进行依次直接插入排序。 141 | 142 | 143 | 144 | 145 | 146 | #### 1、基本思想 147 | 148 | ![](https://itimetraveler.github.io/gallery/sort-algorithms/shell-sort.jpg) 149 | 150 | 151 | 152 | 将待排序数组按照步长gap进行分组,然后将每组的元素利用直接插入排序的方法进行排序;每次再将gap折半减小,循环上述操作;当gap=1时,利用直接插入,完成排序。 153 | 154 | 可以看到步长的选择是希尔排序的重要部分。只要最终步长为1任何步长序列都可以工作。一般来说最简单的步长取值是**初次取数组长度的一半**为增量,之后每次再减半,直到增量为1。更好的步长序列取值可以参考[维基百科](https://zh.wikipedia.org/wiki/%E5%B8%8C%E5%B0%94%E6%8E%92%E5%BA%8F#.E6.AD.A5.E9.95.BF.E5.BA.8F.E5.88.97)。 155 | 156 | #### 2、算法描述 157 | 158 | ①. 选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;(**一般初次取数组半长,之后每次再减半,直到增量为1**)
159 | ②. 按增量序列个数k,对序列进行k 趟排序;
160 | ③. 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。
161 | 162 | #### 3、代码实现 163 | 164 | 以下是我自己的实现,可以看到实现很幼稚,但是好处是理解起来很简单。因为没有经过任何的优化,所以不建议大家直接使用。建议对比下方的维基百科官方实现代码,特别是步长取值策略部分。 165 | 166 | ```java 167 | /** 168 | * 希尔排序 169 | * 170 | * 1. 选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;(一般初次取数组半长,之后每次再减半,直到增量为1) 171 | * 2. 按增量序列个数k,对序列进行k 趟排序; 172 | * 3. 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。 173 | * 仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 174 | * @param arr 待排序数组 175 | */ 176 | public static void shellSort(int[] arr){ 177 | int gap = arr.length / 2; 178 | for (; gap > 0; gap /= 2) { //不断缩小gap,直到1为止 179 | for (int j = 0; (j+gap) < arr.length; j++){ //使用当前gap进行组内插入排序 180 | for(int k = 0; (k+gap)< arr.length; k += gap){ 181 | if(arr[k] > arr[k+gap]) { 182 | int temp = arr[k+gap]; //交换操作 183 | arr[k+gap] = arr[k]; 184 | arr[k] = temp; 185 | System.out.println(" Sorting: " + Arrays.toString(arr)); 186 | } 187 | } 188 | } 189 | } 190 | } 191 | ``` 192 | 193 | 下面是维基百科官方实现,大家注意gap步长取值部分: 194 | 195 | ```java 196 | /** 197 | * 希尔排序(Wiki官方版) 198 | * 199 | * 1. 选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;(注意此算法的gap取值) 200 | * 2. 按增量序列个数k,对序列进行k 趟排序; 201 | * 3. 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。 202 | * 仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 203 | * @param arr 待排序数组 204 | */ 205 | public static void shell_sort(int[] arr) { 206 | int gap = 1, i, j, len = arr.length; 207 | int temp; 208 | while (gap < len / 3) 209 | gap = gap * 3 + 1; // : 1, 4, 13, 40, 121, ... 210 | for (; gap > 0; gap /= 3) { 211 | for (i = gap; i < len; i++) { 212 | temp = arr[i]; 213 | for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap) 214 | arr[j + gap] = arr[j]; 215 | arr[j + gap] = temp; 216 | } 217 | } 218 | } 219 | ``` 220 | 221 | 以下是希尔排序复杂度: 222 | 223 | 224 | | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 225 | | ---------- | ---------- | ---------- | ----- | 226 | | O(nlog2 n) | O(nlog2 n) | O(nlog2 n) | O(1) | 227 | 228 | 229 | 230 | ### 三、选择排序(Selection Sort) 231 | 232 | --- 233 | 234 | > ![选择排序的示例动画。红色表示当前最小值,黄色表示已排序序列,蓝色表示当前位置。](https://itimetraveler.github.io/gallery/sort-algorithms/Selection-Sort-Animation.gif) 235 | 236 | 237 | 238 | 从算法逻辑上看,选择排序是一种简单直观的排序算法,在简单选择排序过程中,所需移动记录的次数比较少。 239 | 240 | #### 1、基本思想 241 | 242 | 选择排序的基本思想:比较 + 交换。 243 | 244 | 在未排序序列中找到最小(大)元素,存放到未排序序列的起始位置。在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种。 245 | 246 | 247 | #### 2、算法描述 248 | 249 | ①. 从待排序序列中,找到关键字最小的元素;
250 | ②. 如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换;
251 | ③. 从余下的 N - 1 个元素中,找出关键字最小的元素,重复①、②步,直到排序结束。
252 | 253 | 254 | #### 3、代码实现 255 | 256 | 选择排序比较简单,以下是我自己的实现,跟官方版差不多,所以完全可以参考。 257 | 258 | ```java 259 | /** 260 | * 选择排序 261 | * 262 | * 1. 从待排序序列中,找到关键字最小的元素; 263 | * 2. 如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换; 264 | * 3. 从余下的 N - 1 个元素中,找出关键字最小的元素,重复①、②步,直到排序结束。 265 | * 仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 266 | * @param arr 待排序数组 267 | */ 268 | public static void selectionSort(int[] arr){ 269 | for(int i = 0; i < arr.length-1; i++){ 270 | int min = i; 271 | for(int j = i+1; j < arr.length; j++){ //选出之后待排序中值最小的位置 272 | if(arr[j] < arr[min]){ 273 | min = j; 274 | } 275 | } 276 | if(min != i){ 277 | int temp = arr[min]; //交换操作 278 | arr[min] = arr[i]; 279 | arr[i] = temp; 280 | System.out.println("Sorting: " + Arrays.toString(arr)); 281 | } 282 | } 283 | } 284 | ``` 285 | 286 | 287 | 以下是选择排序复杂度: 288 | 289 | 290 | | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 291 | | ------- | ----- | ----- | ----- | 292 | | O(n²) | O(n²) | O(n²) | O(1) | 293 | 294 | 295 | 选择排序的简单和直观名副其实,这也造就了它”出了名的慢性子”,无论是哪种情况,哪怕原数组已排序完成,它也将花费将近n²/2次遍历来确认一遍。即便是这样,它的排序结果也还是不稳定的。 唯一值得高兴的是,它并不耗费额外的内存空间。 296 | 297 | 298 | 299 | 300 | ### 四、堆排序(Heap Sort) 301 | 302 | --- 303 | 304 | > 1991年的计算机先驱奖获得者、斯坦福大学计算机科学系教授罗伯特·弗洛伊德(Robert W.Floyd) 和威廉姆斯(J.Williams) 在1964年共同发明了著名的堆排序算法(Heap Sort). 305 | 306 | 堆的定义如下:n个元素的序列{k1,k2,···,kn},当且仅当满足下关系时,称之为堆。 307 | 308 | 309 | 310 | ki <= k(2i)  且   ki <= k(2i+1)
311 | 312 | 或:   ki >= k(2i) 且 ki >= k(2i+1)
313 | 314 | 315 | 把此序列对应的二维数组看成一个完全二叉树。那么堆的含义就是:**完全二叉树中任何一个非叶子节点的值均不大于(或不小于)其左,右孩子节点的值。**由上述性质可知大顶堆的堆顶的关键字肯定是所有关键字中最大的,小顶堆的堆顶的关键字是所有关键字中最小的。因此我们可使用大顶堆进行升序排序, 使用小顶堆进行降序排序。 316 | 317 | 318 | 319 | #### 1、基本思想 320 | 321 | 此处以大顶堆为例,堆排序的过程就是将待排序的序列构造成一个堆,选出堆中最大的移走,再把剩余的元素调整成堆,找出最大的再移走,重复直至有序。 322 | 323 | 324 | #### 2、算法描述 325 | 326 | ①. 先将初始序列K[1..n]建成一个大顶堆, 那么此时第一个元素K1最大, 此堆为初始的无序区.
327 | ②. 再将关键字最大的记录K1 (即堆顶, 第一个元素)和无序区的最后一个记录 Kn 交换, 由此得到新的无序区K[1..n-1]和有序区K[n], 且满足K[1..n-1].keys <= K[n].key
328 | ③. 交换K1 和 Kn 后, 堆顶可能违反堆性质, 因此需将K[1..n-1]调整为堆. 然后重复步骤②, 直到无序区只有一个元素时停止.
329 | 330 | 动图效果如下所示: 331 | 332 | ![堆排序过程](https://itimetraveler.github.io/gallery/sort-algorithms/heap_sort_gif.gif) 333 | 334 | ![堆排序算法的演示。首先,将元素进行重排,以匹配堆的条件。图中排序过程之前简单的绘出了堆树的结构。](https://itimetraveler.github.io/gallery/sort-algorithms/Sorting_heapsort_anim.gif) 335 | 336 | #### 3、代码实现 337 | 338 | 从算法描述来看,堆排序需要两个过程,一是建立堆,二是堆顶与堆的最后一个元素交换位置。所以堆排序有两个函数组成。一是建堆函数,二是反复调用建堆函数以选择出剩余未排元素中最大的数来实现排序的函数。 339 | 340 | 总结起来就是定义了以下几种操作: 341 | 342 | - 最大堆调整(Max_Heapify):将堆的末端子节点作调整,使得子节点永远小于父节点 343 | - 创建最大堆(Build_Max_Heap):将堆所有数据重新排序 344 | - 堆排序(HeapSort):移除位在第一个数据的根节点,并做最大堆调整的递归运算 345 | 346 | 对于堆节点的访问: 347 | 348 | - 父节点i的左子节点在位置:`(2*i+1)`; 349 | - 父节点i的右子节点在位置:`(2*i+2)`; 350 | - 子节点i的父节点在位置:`floor((i-1)/2)`; 351 | 352 | 353 | 354 | ```java 355 | /** 356 | * 堆排序 357 | * 358 | * 1. 先将初始序列K[1..n]建成一个大顶堆, 那么此时第一个元素K1最大, 此堆为初始的无序区. 359 | * 2. 再将关键字最大的记录K1 (即堆顶, 第一个元素)和无序区的最后一个记录 Kn 交换, 由此得到新的无序区K[1..n−1]和有序区K[n], 且满足K[1..n−1].keys⩽K[n].key 360 | * 3. 交换K1 和 Kn 后, 堆顶可能违反堆性质, 因此需将K[1..n−1]调整为堆. 然后重复步骤②, 直到无序区只有一个元素时停止. 361 | * @param arr 待排序数组 362 | */ 363 | public static void heapSort(int[] arr){ 364 | for(int i = arr.length; i > 0; i--){ 365 | max_heapify(arr, i); 366 | 367 | int temp = arr[0]; //堆顶元素(第一个元素)与Kn交换 368 | arr[0] = arr[i-1]; 369 | arr[i-1] = temp; 370 | } 371 | } 372 | 373 | private static void max_heapify(int[] arr, int limit){ 374 | if(arr.length <= 0 || arr.length < limit) return; 375 | int parentIdx = limit / 2; 376 | 377 | for(; parentIdx >= 0; parentIdx--){ 378 | if(parentIdx * 2 >= limit){ 379 | continue; 380 | } 381 | int left = parentIdx * 2; //左子节点位置 382 | int right = (left + 1) >= limit ? left : (left + 1); //右子节点位置,如果没有右节点,默认为左节点位置 383 | 384 | int maxChildId = arr[left] >= arr[right] ? left : right; 385 | if(arr[maxChildId] > arr[parentIdx]){ //交换父节点与左右子节点中的最大值 386 | int temp = arr[parentIdx]; 387 | arr[parentIdx] = arr[maxChildId]; 388 | arr[maxChildId] = temp; 389 | } 390 | } 391 | System.out.println("Max_Heapify: " + Arrays.toString(arr)); 392 | } 393 | ``` 394 | 395 | > **注:** x>>1 是位运算中的右移运算, 表示右移一位, 等同于x除以2再取整, 即 x>>1 == Math.floor(x/2) . 396 | 397 | 以上, 398 | ①. 建立堆的过程, 从length/2 一直处理到0, 时间复杂度为O(n); 399 | ②. 调整堆的过程是沿着堆的父子节点进行调整, 执行次数为堆的深度, 时间复杂度为O(lgn); 400 | ③. 堆排序的过程由n次第②步完成, 时间复杂度为O(nlgn). 401 | 402 | 403 | | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 404 | | --------- | --------- | --------- | ----- | 405 | | O(nlog2n) | O(nlog2n) | O(nlog2n) | O(1) | 406 | 407 | Tips: **由于堆排序中初始化堆的过程比较次数较多, 因此它不太适用于小序列.** 同时由于多次任意下标相互交换位置, 相同元素之间原本相对的顺序被破坏了, 因此, 它是不稳定的排序. 408 | 409 | 410 | 411 | 412 | ### 五、冒泡排序(Bubble Sort) 413 | 414 | --- 415 | 416 | ![冒泡排序的思想](https://itimetraveler.github.io/gallery/sort-algorithms/bubble-sort02.gif) 417 | 418 | 419 | > 我想对于它每个学过C语言的都会了解,这可能是很多人接触的第一个排序算法。 420 | 421 | 422 | #### 1、基本思想 423 | 424 | 冒泡排序(Bubble Sort)是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。 425 | 426 | 427 | ![冒泡排序演示](https://itimetraveler.github.io/gallery/sort-algorithms/bubble-sort.gif) 428 | 429 | 430 | #### 2、算法描述 431 | 432 | 冒泡排序算法的运作如下: 433 | 434 | ①. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
435 | ②. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
436 | ③. 针对所有的元素重复以上的步骤,除了最后一个。
437 | ④. 持续每次对越来越少的元素重复上面的步骤①~③,直到没有任何一对数字需要比较。
438 | 439 | #### 3、代码实现 440 | 441 | 442 | 冒泡排序需要两个嵌套的循环. 其中, **外层循环**移动游标; **内层循环**遍历游标及之后(或之前)的元素, 通过两两交换的方式, 每次只确保该内循环结束位置排序正确, 然后内层循环周期结束, 交由外层循环往后(或前)移动游标, 随即开始下一轮内层循环, 以此类推, 直至循环结束. 443 | 444 | 445 | 446 | ```java 447 | /** 448 | * 冒泡排序 449 | * 450 | * ①. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 451 | * ②. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。 452 | * ③. 针对所有的元素重复以上的步骤,除了最后一个。 453 | * ④. 持续每次对越来越少的元素重复上面的步骤①~③,直到没有任何一对数字需要比较。 454 | * @param arr 待排序数组 455 | */ 456 | public static void bubbleSort(int[] arr){ 457 | for (int i = arr.length - 1; i > 0; i--) { //外层循环移动游标 458 | for(int j = 0; j < i; j++){ //内层循环遍历游标及之后(或之前)的元素 459 | if(arr[j] > arr[j+1]){ 460 | int temp = arr[j]; 461 | arr[j] = arr[j+1]; 462 | arr[j+1] = temp; 463 | System.out.println("Sorting: " + Arrays.toString(arr)); 464 | } 465 | } 466 | } 467 | } 468 | ``` 469 | 470 | 471 | 472 | 以下是冒泡排序算法复杂度: 473 | 474 | 475 | | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 476 | | ------- | ---- | ----- | ----- | 477 | | O(n²) | O(n) | O(n²) | O(1) | 478 | 479 | 冒泡排序是最容易实现的排序, 最坏的情况是每次都需要交换, 共需遍历并交换将近n²/2次, 时间复杂度为O(n²). 最佳的情况是内循环遍历一次后发现排序是对的, 因此退出循环, 时间复杂度为O(n). 平均来讲, 时间复杂度为O(n²). 由于冒泡排序中只有缓存的temp变量需要内存空间, 因此空间复杂度为常量O(1). 480 | 481 | Tips: 由于冒泡排序只在相邻元素大小不符合要求时才调换他们的位置, 它并不改变相同元素之间的相对顺序, 因此它是稳定的排序算法. 482 | 483 | 484 | 485 | 486 | ### 六、快速排序(Quick Sort) 487 | 488 | --- 489 | 490 | 快速排序(Quicksort)是对冒泡排序的一种改进,借用了分治的思想,由C. A. R. Hoare在1962年提出。 491 | 492 | #### 1、基本思想 493 | 494 | 快速排序的基本思想:**挖坑填数+分治法**。 495 | 496 | 首先选一个轴值(pivot,也有叫基准的),通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。 497 | 498 | ![使用快速排序法对一列数字进行排序的过程](https://itimetraveler.github.io/gallery/sort-algorithms/Sorting_quicksort_anim.gif) 499 | 500 | #### 2、算法描述 501 | 502 | 快速排序使用分治策略来把一个序列(list)分为两个子序列(sub-lists)。步骤为: 503 | 504 | ①. 从数列中挑出一个元素,称为"基准"(pivot)。
505 | ②. 重新排序数列,所有比基准值小的元素摆放在基准前面,所有比基准值大的元素摆在基准后面(相同的数可以到任一边)。在这个分区结束之后,该基准就处于数列的中间位置。这个称为分区(partition)操作。
506 | ③. 递归地(recursively)把小于基准值元素的子数列和大于基准值元素的子数列排序。
507 | 508 | 递归到最底部时,数列的大小是零或一,也就是已经排序好了。这个算法一定会结束,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。 509 | 510 | 511 | 512 | ![快速排序演示](https://itimetraveler.github.io/gallery/sort-algorithms/quick-sort09.gif) 513 | 514 | 515 | #### 3、代码实现 516 | 517 | 用伪代码描述如下: 518 | 519 | ①. `i = L; j = R;` 将基准数挖出形成第一个坑`a[i]`。
520 | ②.`j--`,由后向前找比它小的数,找到后挖出此数填前一个坑`a[i]`中。
521 | ③.`i++`,由前向后找比它大的数,找到后也挖出此数填到前一个坑`a[j]`中。
522 | ④.再重复执行②,③二步,直到`i==j`,将基准数填入`a[i]`中
523 | 524 | 525 | 526 | 527 | ![快速排序采用“分而治之、各个击破”的观念,此为原地(In-place)分区版本。](https://itimetraveler.github.io/gallery/sort-algorithms/200px-Partition_example.svg.png) 528 | 529 | 530 | ```java 531 | /** 532 | * 快速排序(递归) 533 | * 534 | * ①. 从数列中挑出一个元素,称为"基准"(pivot)。 535 | * ②. 重新排序数列,所有比基准值小的元素摆放在基准前面,所有比基准值大的元素摆在基准后面(相同的数可以到任一边)。在这个分区结束之后,该基准就处于数列的中间位置。这个称为分区(partition)操作。 536 | * ③. 递归地(recursively)把小于基准值元素的子数列和大于基准值元素的子数列排序。 537 | * @param arr 待排序数组 538 | * @param low 左边界 539 | * @param high 右边界 540 | */ 541 | public static void quickSort(int[] arr, int low, int high){ 542 | if(arr.length <= 0) return; 543 | if(low >= high) return; 544 | int left = low; 545 | int right = high; 546 | 547 | int temp = arr[left]; //挖坑1:保存基准的值 548 | while (left < right){ 549 | while(left < right && arr[right] >= temp){ //坑2:从后向前找到比基准小的元素,插入到基准位置坑1中 550 | right--; 551 | } 552 | arr[left] = arr[right]; 553 | while(left < right && arr[left] <= temp){ //坑3:从前往后找到比基准大的元素,放到刚才挖的坑2中 554 | left++; 555 | } 556 | arr[right] = arr[left]; 557 | } 558 | arr[left] = temp; //基准值填补到坑3中,准备分治递归快排 559 | System.out.println("Sorting: " + Arrays.toString(arr)); 560 | quickSort(arr, low, left-1); 561 | quickSort(arr, left+1, high); 562 | } 563 | ``` 564 | 上面是递归版的快速排序:通过把基准temp插入到合适的位置来实现分治,并递归地对分治后的两个划分继续快排。那么非递归版的快排如何实现呢? 565 | 566 | 因为**递归的本质是栈**,所以我们非递归实现的过程中,可以借助栈来保存中间变量就可以实现非递归了。在这里中间变量也就是通过Pritation函数划分区间之后分成左右两部分的首尾指针,只需要保存这两部分的首尾指针即可。 567 | 568 | ```java 569 | /** 570 | * 快速排序(非递归) 571 | * 572 | * ①. 从数列中挑出一个元素,称为"基准"(pivot)。 573 | * ②. 重新排序数列,所有比基准值小的元素摆放在基准前面,所有比基准值大的元素摆在基准后面(相同的数可以到任一边)。在这个分区结束之后,该基准就处于数列的中间位置。这个称为分区(partition)操作。 574 | * ③. 把分区之后两个区间的边界(low和high)压入栈保存,并循环①、②步骤 575 | * @param arr 待排序数组 576 | */ 577 | public static void quickSortByStack(int[] arr){ 578 | if(arr.length <= 0) return; 579 | Stack stack = new Stack(); 580 | 581 | //初始状态的左右指针入栈 582 | stack.push(0); 583 | stack.push(arr.length - 1); 584 | while(!stack.isEmpty()){ 585 | int high = stack.pop(); //出栈进行划分 586 | int low = stack.pop(); 587 | 588 | int pivotIdx = partition(arr, low, high); 589 | 590 | //保存中间变量 591 | if(pivotIdx > low) { 592 | stack.push(low); 593 | stack.push(pivotIdx - 1); 594 | } 595 | if(pivotIdx < high && pivotIdx >= 0){ 596 | stack.push(pivotIdx + 1); 597 | stack.push(high); 598 | } 599 | } 600 | } 601 | 602 | private static int partition(int[] arr, int low, int high){ 603 | if(arr.length <= 0) return -1; 604 | if(low >= high) return -1; 605 | int l = low; 606 | int r = high; 607 | 608 | int pivot = arr[l]; //挖坑1:保存基准的值 609 | while(l < r){ 610 | while(l < r && arr[r] >= pivot){ //坑2:从后向前找到比基准小的元素,插入到基准位置坑1中 611 | r--; 612 | } 613 | arr[l] = arr[r]; 614 | while(l < r && arr[l] <= pivot){ //坑3:从前往后找到比基准大的元素,放到刚才挖的坑2中 615 | l++; 616 | } 617 | arr[r] = arr[l]; 618 | } 619 | arr[l] = pivot; //基准值填补到坑3中,准备分治递归快排 620 | return l; 621 | } 622 | ``` 623 | 624 | 快速排序是通常被认为在同数量级(O(nlog2n))的排序方法中平均性能最好的。但若初始序列按关键码有序或基本有序时,快排序反而蜕化为冒泡排序。为改进之,通常以“三者取中法”来选取基准记录,即将排序区间的两个端点与中点三个记录关键码居中的调整为支点记录。快速排序是一个不稳定的排序方法。 625 | 626 | 627 | 以下是快速排序算法复杂度: 628 | 629 | 630 | | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 631 | | --------- | --------- | ----- | ------------- | 632 | | O(nlog₂n) | O(nlog₂n) | O(n²) | O(1)(原地分区递归版) | 633 | 634 | 635 | 快速排序排序效率非常高。 虽然它运行最糟糕时将达到O(n²)的时间复杂度, 但通常平均来看, 它的时间复杂为O(nlogn), 比同样为O(nlogn)时间复杂度的归并排序还要快. 快速排序似乎更偏爱乱序的数列, 越是乱序的数列, 它相比其他排序而言, 相对效率更高. 636 | 637 | Tips: 同选择排序相似, 快速排序每次交换的元素都有可能不是相邻的, 因此它有可能打破原来值为相同的元素之间的顺序. 因此, 快速排序并不稳定. 638 | 639 | 640 | 641 | 642 | 643 | 644 | ### 七、归并排序(Merging Sort) 645 | 646 | --- 647 | 648 | 649 | 650 | ![](https://itimetraveler.github.io/gallery/sort-algorithms/merging-sort_sample.jpg) 651 | 652 | 653 | 654 | 归并排序是建立在归并操作上的一种有效的排序算法,1945年由约翰·冯·诺伊曼首次提出。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用,且各层分治递归可以同时进行。 655 | 656 | 657 | #### 1、基本思想 658 | 659 | 归并排序算法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。 660 | 661 | 662 | 663 | ![这个图很有概括性,来自维基](https://itimetraveler.github.io/gallery/sort-algorithms/2016-07-15_归并排序.gif) 664 | 665 | #### 2、算法描述 666 | 667 | 668 | **归并排序可通过两种方式实现:** 669 | 670 | - 自上而下的递归 671 | - 自下而上的迭代 672 | 673 | 674 | **一、递归法**(假设序列共有n个元素): 675 | 676 | ①. 将序列每相邻两个数字进行归并操作,形成 floor(n/2)个序列,排序后每个序列包含两个元素;
677 | ②. 将上述序列再次归并,形成 floor(n/4)个序列,每个序列包含四个元素;
678 | ③. 重复步骤②,直到所有元素排序完毕。
679 | 680 | 681 | ![](https://itimetraveler.github.io/gallery/sort-algorithms/merging-sort.gif) 682 | 683 | 684 | **二、迭代法** 685 | 686 | ①. 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
687 | ②. 设定两个指针,最初位置分别为两个已经排序序列的起始位置
688 | ③. 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
689 | ④. 重复步骤③直到某一指针到达序列尾
690 | ⑤. 将另一序列剩下的所有元素直接复制到合并序列尾
691 | 692 | #### 3、代码实现 693 | 694 | 归并排序其实要做两件事: 695 | 696 | - 分解:将序列每次折半拆分 697 | - 合并:将划分后的序列段两两排序合并 698 | 699 | 因此,归并排序实际上就是两个操作,拆分+合并 700 | 701 | **如何合并?** 702 | 703 | L[first...mid]为第一段,L[mid+1...last]为第二段,并且两端已经有序,现在我们要将两端合成达到L[first...last]并且也有序。 704 | 705 | 首先依次从第一段与第二段中取出元素比较,将较小的元素赋值给temp[]
706 | 重复执行上一步,当某一段赋值结束,则将另一段剩下的元素赋值给temp[]
707 | 此时将temp[]中的元素复制给L[],则得到的L[first...last]有序
708 | 709 | **如何分解?** 710 | 711 | 在这里,我们采用递归的方法,首先将待排序列分成A,B两组;然后重复对A、B序列 712 | 分组;直到分组后组内只有一个元素,此时我们认为组内所有元素有序,则分组结束。 713 | 714 | 715 | 这里我写了递归算法如下: 716 | 717 | ```java 718 | /** 719 | * 归并排序(递归) 720 | * 721 | * ①. 将序列每相邻两个数字进行归并操作,形成 floor(n/2)个序列,排序后每个序列包含两个元素; 722 | * ②. 将上述序列再次归并,形成 floor(n/4)个序列,每个序列包含四个元素; 723 | * ③. 重复步骤②,直到所有元素排序完毕。 724 | * @param arr 待排序数组 725 | */ 726 | public static int[] mergingSort(int[] arr){ 727 | if(arr.length <= 1) return arr; 728 | 729 | int num = arr.length >> 1; 730 | int[] leftArr = Arrays.copyOfRange(arr, 0, num); 731 | int[] rightArr = Arrays.copyOfRange(arr, num, arr.length); 732 | System.out.println("split two array: " + Arrays.toString(leftArr) + " And " + Arrays.toString(rightArr)); 733 | return mergeTwoArray(mergingSort(leftArr), mergingSort(rightArr)); //不断拆分为最小单元,再排序合并 734 | } 735 | 736 | private static int[] mergeTwoArray(int[] arr1, int[] arr2){ 737 | int i = 0, j = 0, k = 0; 738 | int[] result = new int[arr1.length + arr2.length]; //申请额外的空间存储合并之后的数组 739 | while(i < arr1.length && j < arr2.length){ //选取两个序列中的较小值放入新数组 740 | if(arr1[i] <= arr2[j]){ 741 | result[k++] = arr1[i++]; 742 | }else{ 743 | result[k++] = arr2[j++]; 744 | } 745 | } 746 | while(i < arr1.length){ //序列1中多余的元素移入新数组 747 | result[k++] = arr1[i++]; 748 | } 749 | while(j < arr2.length){ //序列2中多余的元素移入新数组 750 | result[k++] = arr2[j++]; 751 | } 752 | System.out.println("Merging: " + Arrays.toString(result)); 753 | return result; 754 | } 755 | ``` 756 | 757 | 由上, 长度为n的数组, 最终会调用mergeSort函数2n-1次。**通过自上而下的递归实现的归并排序, 将存在堆栈溢出的风险。** 758 | 759 | 以下是归并排序算法复杂度: 760 | 761 | | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 762 | | --------- | --------- | --------- | ----- | 763 | | O(nlog₂n) | O(nlog₂n) | O(nlog₂n) | O(n) | 764 | 765 | 从效率上看,归并排序可算是排序算法中的”佼佼者”. 假设数组长度为n,那么拆分数组共需logn,, 又每步都是一个普通的合并子数组的过程, 时间复杂度为O(n), 故其综合时间复杂度为O(nlogn)。另一方面, 归并排序多次递归过程中拆分的子数组需要保存在内存空间, 其空间复杂度为O(n)。 766 | 767 | 768 | > 和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是`O(n log n)`的时间复杂度。代价是需要额外的内存空间。 769 | 770 | 771 | 772 | 773 | ### 八、基数排序(Radix Sort) 774 | 775 | --- 776 | 777 | 基数排序的发明可以追溯到1887年赫尔曼·何乐礼在打孔卡片制表机(Tabulation Machine), 排序器每次只能看到一个列。它是基于元素值的每个位上的字符来排序的。 对于数字而言就是分别基于个位,十位, 百位或千位等等数字来排序。 778 | 779 | 基数排序(Radix sort)是一种非比较型整数排序算法,其原理是将整数按位数切割成不同的数字,然后按每个位数分别比较。由于整数也可以表达字符串(比如名字或日期)和特定格式的浮点数,所以基数排序也不是只能使用于整数。 780 | 781 | #### 1、基本思想 782 | 783 | 它是这样实现的:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。 784 | 785 | 786 | 基数排序按照优先从高位或低位来排序有两种实现方案: 787 | 788 | - **MSD(Most significant digital) 从最左侧高位开始进行排序**。先按k1排序分组, 同一组中记录, 关键码k1相等, 再对各组按k2排序分成子组, 之后, 对后面的关键码继续这样的排序分组, 直到按最次位关键码kd对各子组排序后. 再将各组连接起来, 便得到一个有序序列。*MSD方式适用于位数多的序列*。 789 | 790 | - **LSD (Least significant digital)从最右侧低位开始进行排序**。先从kd开始排序,再对kd-1进行排序,依次重复,直到对k1排序后便得到一个有序序列。*LSD方式适用于位数少的序列*。 791 | 792 | ![基数排序LSD动图演示](https://itimetraveler.github.io/gallery/sort-algorithms/radix-sort_sample.gif) 793 | 794 | 795 | #### 2、算法描述 796 | 797 | 我们以LSD为例,从最低位开始,具体算法描述如下: 798 | 799 | ①. 取得数组中的最大数,并取得位数;
800 | ②. arr为原始数组,从最低位开始取每个位组成radix数组;
801 | ③. 对radix进行计数排序(利用计数排序适用于小范围数的特点);
802 | 803 | #### 3、代码实现 804 | 805 | 基数排序:通过序列中各个元素的值,对排序的N个元素进行若干趟的“分配”与“收集”来实现排序。 806 | 807 | - **分配**:我们将L[i]中的元素取出,首先确定其个位上的数字,根据该数字分配到与之序号相同的桶中 808 | 809 | - **收集**:当序列中所有的元素都分配到对应的桶中,再按照顺序依次将桶中的元素收集形成新的一个待排序列L[]。对新形成的序列L[]重复执行分配和收集元素中的十位、百位...直到分配完该序列中的最高位,则排序结束 810 | 811 | 812 | 813 | ```java 814 | /** 815 | * 基数排序(LSD 从低位开始) 816 | * 817 | * 基数排序适用于: 818 | * (1)数据范围较小,建议在小于1000 819 | * (2)每个数值都要大于等于0 820 | * 821 | * ①. 取得数组中的最大数,并取得位数; 822 | * ②. arr为原始数组,从最低位开始取每个位组成radix数组; 823 | * ③. 对radix进行计数排序(利用计数排序适用于小范围数的特点); 824 | * @param arr 待排序数组 825 | */ 826 | public static void radixSort(int[] arr){ 827 | if(arr.length <= 1) return; 828 | 829 | //取得数组中的最大数,并取得位数 830 | int max = 0; 831 | for(int i = 0; i < arr.length; i++){ 832 | if(max < arr[i]){ 833 | max = arr[i]; 834 | } 835 | } 836 | int maxDigit = 1; 837 | while(max / 10 > 0){ 838 | maxDigit++; 839 | max = max / 10; 840 | } 841 | System.out.println("maxDigit: " + maxDigit); 842 | 843 | //申请一个桶空间 844 | int[][] buckets = new int[10][arr.length]; 845 | int base = 10; 846 | 847 | //从低位到高位,对每一位遍历,将所有元素分配到桶中 848 | for(int i = 0; i < maxDigit; i++){ 849 | int[] bktLen = new int[10]; //存储各个桶中存储元素的数量 850 | 851 | //分配:将所有元素分配到桶中 852 | for(int j = 0; j < arr.length; j++){ 853 | int whichBucket = (arr[j] % base) / (base / 10); 854 | buckets[whichBucket][bktLen[whichBucket]] = arr[j]; 855 | bktLen[whichBucket]++; 856 | } 857 | 858 | //收集:将不同桶里数据挨个捞出来,为下一轮高位排序做准备,由于靠近桶底的元素排名靠前,因此从桶底先捞 859 | int k = 0; 860 | for(int b = 0; b < buckets.length; b++){ 861 | for(int p = 0; p < bktLen[b]; p++){ 862 | arr[k++] = buckets[b][p]; 863 | } 864 | } 865 | 866 | System.out.println("Sorting: " + Arrays.toString(arr)); 867 | base *= 10; 868 | } 869 | } 870 | ``` 871 | 872 | 以下是基数排序算法复杂度,其中k为最大数的位数: 873 | 874 | | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 875 | | ---------- | ---------- | ---------- | ------ | 876 | | O(d*(n+r)) | O(d*(n+r)) | O(d*(n+r)) | O(n+r) | 877 | 878 | 879 | 其中,**d 为位数,r 为基数,n 为原数组个数**。在基数排序中,因为没有比较操作,所以在复杂上,最好的情况与最坏的情况在时间上是一致的,均为 `O(d*(n + r))`。 880 | 881 | 基数排序更适合用于对时间, 字符串等这些**整体权值未知的数据**进行排序。 882 | 883 | Tips: 基数排序不改变相同元素之间的相对顺序,因此它是稳定的排序算法。 884 | 885 | 886 | **基数排序 vs 计数排序 vs 桶排序** 887 | 888 | 这三种排序算法都利用了桶的概念,但对桶的使用方法上有明显差异: 889 | 890 | 1. 基数排序:根据键值的每位数字来分配桶 891 | 2. 计数排序:每个桶只存储单一键值 892 | 3. 桶排序:每个桶存储一定范围的数值 893 | 894 | 895 | 896 | ### 总结 897 | 898 | --- 899 | 900 | 各种排序性能对比如下图,有些排序未详细介绍,暂且放到这里。 901 | 实例测试结果可以看这里:[**八大排序算法耗时对比**](https://github.com/iTimeTraveler/SortAlgorithms/blob/master/BENCH_RESULT.md) 。 902 | 903 | 904 | | 排序类型 | 平均情况 | 最好情况 | 最坏情况 | 辅助空间 | 稳定性 | 905 | | ------ | --------- | --------- | ---------- | --------- | ----- | 906 | | 冒泡排序 | O(n²) | O(n) | O(n²) | O(1) | 稳定 | 907 | | 选择排序 | O(n²) | O(n²) | O(n²) | O(1) | 不稳定 | 908 | | 直接插入排序 | O(n²) | O(n) | O(n²) | O(1) | 稳定 | 909 | | 折半插入排序 | O(n²) | O(n) | O(n²) | O(1) | 稳定 | 910 | | 希尔排序 | O(n^1.3) | O(nlogn) | O(n²) | O(1) | 不稳定 | 911 | | 归并排序 | O(nlog₂n) | O(nlog₂n) | O(nlog₂n) | O(n) | 稳定 | 912 | | 快速排序 | O(nlog₂n) | O(nlog₂n) | O(n²) | O(nlog₂n) | 不稳定 | 913 | | 堆排序 | O(nlog₂n) | O(nlog₂n) | O(nlog₂n) | O(1) | 不稳定 | 914 | | 计数排序 | O(n+k) | O(n+k) | O(n+k) | O(k) | 稳定 | 915 | | 桶排序 | O(n+k) | O(n+k) | O(n²) | O(n+k) | (不)稳定 | 916 | | 基数排序 | O(d(n+k)) | O(d(n+k)) | O(d(n+kd)) | O(n+kd) | 稳定 | 917 | 918 | 919 | 从时间复杂度来说: 920 | 921 | (1). 平方阶O(n²)排序:**`各类简单排序:直接插入、直接选择和冒泡排序`**; 922 | 923 | (2). 线性对数阶O(nlog₂n)排序:**` 快速排序、堆排序和归并排序`**; 924 | 925 | (3). O(n1+§))排序,§是介于0和1之间的常数:**`希尔排序`** 926 | 927 | (4). 线性阶O(n)排序:**`基数排序,此外还有桶、箱排序`**。 928 | 929 | 930 | 到此,很多人会注意到**基数排序**的时间复杂度是最小的,那么为什么却没有快排、堆排序流行呢?我们看看下图算法导论的相关说明: 931 | 932 | ![](https://itimetraveler.github.io/gallery/sort-algorithms/radixsort-comparison.jpg) 933 | 934 | 基数排序只适用于有基数的情况,而基于比较的排序适用范围就广得多。另一方面是内存上的考虑。作为一种通用的排序方法,最好不要带来意料之外的内存开销,所以各语言的默认实现都没有用基数排序,但是不能否认基数排序在各领域的应用。 935 | 936 | 937 | #### 时间复杂度极限 938 | 939 | **当被排序的数有一些性质的时候**(比如是整数,比如有一定的范围),排序算法的复杂度是可以小于O(nlgn)的。比如: 940 | 941 | 1. 计数排序 复杂度O( k+n) 要求:被排序的数是0~k范围内的整数 942 | 2. 基数排序 复杂度O( d(k+n) ) 要求:d位数,每个数位有k个取值 943 | 3. 桶排序 复杂度 O( n ) (平均) 要求:被排序数在某个范围内,并且服从均匀分布 944 | 945 | 但是,当被排序的数不具有任何性质的时候,一般使用基于比较的排序算法,而**基于比较的排序算法时间复杂度的下限必须是O(nlgn)**。 参考[很多高效排序算法的代价是 nlogn,难道这是排序算法的极限了吗?](https://www.zhihu.com/question/24516934) 946 | 947 | 948 | #### 说明 949 | 950 | - 当原表有序或基本有序时,直接插入排序和冒泡排序将大大减少比较次数和移动记录的次数,时间复杂度可降至O(n); 951 | - 而快速排序则相反,当原表基本有序时,将蜕化为冒泡排序,时间复杂度提高为O(n2); 952 | - 原表是否有序,对简单选择排序、堆排序、归并排序和基数排序的时间复杂度影响不大。 953 | 954 | 955 | ![](https://itimetraveler.github.io/gallery/sort-algorithms/2016-07-15_常用排序算法.png) 956 | 957 | 958 | 959 | ### 参考资料 960 | 961 | - 数据结构可视化:[visualgo](https://visualgo.net/zh),[Sorting Algorithms Animations](https://www.toptal.com/developers/sorting-algorithms/),[CodePen](https://codepen.io/iTimeTraveler/pen/dRrwZr) & [sort it out](https://codepen.io/iTimeTraveler/pen/weORyW) 962 | - [一个显示排序过程的PYTHON脚本](https://coolshell.cn/articles/536.html) 963 | - 排序算法测试:[Lab 1: Sorting - 哥德堡大学课件(University of Gothenburg)](http://www.cse.chalmers.se/edu/course/DIT960/lab1-sorting.html) 964 | - [Sorting Algorithm Animations - 一个排序算法比较的网站](http://www.sorting-algorithms.com/) 965 | - [Sorting - 卡内基梅隆大学课件](https://www.cs.cmu.edu/~adamchik/15-121/lectures/Sorting%20Algorithms/sorting.html) 966 | - [数据结构常见的八大排序算法(详细整理)](http://www.jianshu.com/p/7d037c332a9d) 967 | - [必须知道的八大种排序算法【java实现】](http://www.jianshu.com/p/8c915179fd02) 968 | - [十大经典排序算法](http://web.jobbole.com/87968/) 969 | - [视觉直观感受 7 种常用的排序算法](http://blog.jobbole.com/11745/) 970 | - [JS中可能用得到的全部的排序算法](http://louiszhai.github.io/2016/12/23/sort/) 971 | - [总结5种比较高效常用的排序算法](http://www.cnblogs.com/minkaihui/p/4077888.html) 972 | - [常见排序算法C++总结](http://www.cnblogs.com/zyb428/p/5673738.html) 973 | --------------------------------------------------------------------------------