Java使用二分插入排序竟然和直接插入排序速度比較__Java

來源:互聯網
上載者:User
Java使用二分插入排序竟然和直接插入排序速度比較


之前測試過Python使用二分插入排序竟然比直接插入排序快99倍。

現在測試下 Java,Linux測試結果如下:

javac test.java

java test
InsertSort total milliseconds:15769
InsertSortWithBinarySerach total milliseconds:15657

更正下,上面的資料在一台虛擬機器上測試的,所以樣本不夠,理論上,這兩個演算法的速度應該是有倍數差別的。

感謝執筆記憶的空白的指正,再次感謝評論的朋友。

以下是執筆記憶的空白的測試結果:

InsertSort total milliseconds:41496
InsertSortWithBinarySerach total milliseconds:10166


程式如下:

import java.util.Date;public class test{    public static void main(String []args){       Date d1 = new Date();       int[] a = new int[200000];       for(int i=0;i<200000;i++)       {       a[i]=100-i;       }       InsertSort(a);       Date d2 = new Date();       System.out.println("InsertSort total milliseconds:"+(d2.getTime()-d1.getTime()));  //printing the elements //for(int i=0;i<a.length;i++){ //System.out.println(i+" : "+a[i]); //}       Date d3 = new Date();       int[] a2 = new int[200000];       for(int i=0;i<200000;i++)       {       a2[i]=100-i;       }       InsertSortWithBinarySerach(a2);       Date d4 = new Date();       System.out.println("InsertSortWithBinarySerach total milliseconds:"+(d4.getTime()-d3.getTime()));  //printing the elements //for(int j=0;j<a2.length;j++){ //System.out.println(j+" : "+a2[j]); //}    }   public static void InsertSort(int[] A){     for(int i = 1; i < A.length; i++){       int value = A[i];       int j = i - 1;       while(j >= 0 && A[j] > value){         A[j + 1] = A[j];         j = j - 1;       }       A[j + 1] = value;     }   } public static void InsertSortWithBinarySerach(int[] A){    for(int i=1;i<A.length;i++){     int key=A[i];     int pos=binarySearch(A,0,i-1,key); //finds where the element will be stored     for(int j=i;j>pos;j--) //shifts the other elements by 1 position to the right     A[j]=A[j-1];     A[pos]=key; //places the key element in the pos position     } } //uses binary search technique to find the position where the element will be inserted public static int binarySearch(int[] A,int low,int high,int key){     int mid;     while(low<=high){         mid=(low+high)/2;         if(key>A[mid])             low=mid+1;         else if(key<A[mid])             high=mid-1;         else             return mid;    }    return low; }} 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.