`
温柔一刀
  • 浏览: 857432 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

insertion-sort

阅读更多
输入:n个double类型数{a1,a2,......an}
输出:输入序列的一个排列{A1,A2,......An},使得A1<=A2<=......An.

测试代码:
java 代码
 
  1. private InsertionSort insertSort = new InsertionSort();  
  2.   
  3.     public void testOneElementSort() {  
  4.         double[] array = { 3 };  
  5.         array = insertSort.sort(array);  
  6.         assertEquals(3.0, array[0]);  
  7.     }  
  8.   
  9.     public void testTwoElementSort() {  
  10.         double[] array = { 32 };  
  11.         array = insertSort.sort(array);  
  12.         assertEquals(2.0, array[0]);  
  13.         assertEquals(3.0, array[1]);  
  14.     }  
  15.   
  16.     public void testNElementSort() {  
  17.         int n = 200000;  
  18.         double[] array = new double[n];  
  19.         for(int i = 0; i<n;i++){  
  20.             array[i] = Math.random();  
  21.         }  
  22.         array = insertSort.sort(array);  
  23.         for (int i = 1; i < array.length; i++) {  
  24.             assertTrue(array[i] > array[i - 1]);  
  25.         }  
  26.     }  

实现:
java 代码
 
  1. public double[] sort(double[] array) {  
  2.         for (int i = 1; i < array.length; i++) {  
  3.             double key = array[i];  
  4.             int j = i - 1;  
  5.             while (j >= 0 && array[j] > key) {  
  6.                 array[j + 1] = array[j];  
  7.                 j = j - 1;  
  8.             }  
  9.             array[j + 1] = key;  
  10.         }  
  11.         return array;  
  12.     }  

该算法所需的时间大致正比于n×n。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics