转载自:http://blog.csdn.net/sunxing007/article/details/9005471
周末天气不好,在家无事,把常用排序算法理了一遍,收获不小,特写文章纪念。这些算法在学校的时候学过一遍,很多原理都忘记了。现在再回过头理解,结合自己的体会, 选用最佳的方式描述这些算法,以方便理解它们的工作原理和程序设计技巧。本文适合做java面试准备的材料阅读。
先附上一个测试报告:
- Array length: 20000
- bubbleSort : 766 ms
- bubbleSortAdvanced : 662 ms
- bubbleSortAdvanced2 : 647 ms
- selectSort : 252 ms
- insertSort : 218 ms
- insertSortAdvanced : 127 ms
- insertSortAdvanced2 : 191 ms
- binaryTreeSort : 3 ms
- shellSort : 2 ms
- shellSortAdvanced : 2 ms
- shellSortAdvanced2 : 1 ms
- mergeSort : 3 ms
- quickSort : 1 ms
- heapSort : 2 ms
通过测试,可以认为,冒泡排序完全有理由扔进垃圾桶。它存在的唯一理由可能是最好理解。希尔排序的高效性是我没有想到的;堆排序比较难理解和编写,要有宏观的思维。
- package algorithm.sort;
- import java.lang.reflect.Method;
- import java.util.Arrays;
- import java.util.Date;
- /**
- * Java常用排序算法及性能测试集合
- *
- * 本程序集合涵盖常用排序算法的编写,并在注释中配合极其简单的特例讲解了各种算法的工作原理,以方便理解和吸收;
- * 程序编写过程中吸收了很多维基百科和别人blog上面的例子,并结合自己的思考,选择或改进一个最容易让人理解的写法。
- * 同时包含一个集中式的性能测试和正确性测试方法,方便观测。
- * @author http://blog.csdn.net/sunxing007
- * 转载请注明来自http://blog.csdn.net/sunxing007
- */
- public class SortUtil {
- // 被测试的方法集合
- static String[] methodNames = new String[]{
- "bubbleSort",
- "bubbleSortAdvanced",
- "bubbleSortAdvanced2",
- "selectSort",
- "insertSort",
- "insertSortAdvanced",
- "insertSortAdvanced2",
- "binaryTreeSort",
- "shellSort",
- "shellSortAdvanced",
- "shellSortAdvanced2",
- "mergeSort",
- "quickSort",
- "heapSort"
- };
- public static void main(String[] args) throws Exception{
- //correctnessTest();
- performanceTest(20000);
- }
- /**
- * 正确性测试<br>
- * 简单地测试一下各个算法的正确性<br>
- * 只是为了方便观测新添加的算法是否基本正确;<br>
- * @throws Exception 主要是反射相关的Exception;<br>
- */
- public static void correctnessTest() throws Exception{
- int len = 10;
- int[] a = new int[len];
- for(int i=0; i<methodNames.length; i++){
- for(int j=0; j<a.length; j++){
- a[j] = (int)Math.floor(Math.random()*len*2);
- }
- Method sortMethod = null;
- sortMethod = SortUtil.class.getDeclaredMethod(methodNames[i], a.getClass());
- Object o = sortMethod.invoke(null, a);
- System.out.print(methodNames[i] + " : ");
- if(o==null){
- System.out.println(Arrays.toString(a));
- }
- else{
- //兼顾mergeSort,它的排序结果以返回值的形式出现;
- System.out.println(Arrays.toString((int[])o));
- }
- }
- }
- /**
- * 性能测试<br>
- * 数组长度用参数len传入,每个方法跑20遍取耗时平均值;<br>
- * @param len 数组长度 建议取10000以上,否则有些算法会显示耗时为0;<br>
- * @throws Exception 主要是反射相关的Exception;<br>
- */
- public static void performanceTest(int len) throws Exception{
- int[] a = new int[len];
- int times = 20;
- System.out.println("Array length: " + a.length);
- for(int i=0; i<methodNames.length; i++){
- Method sortMethod = null;
- sortMethod = SortUtil.class.getDeclaredMethod(methodNames[i], a.getClass());