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;
}
}