Java使用二分插入排序竟然和直接插入排序速度相差不多
2016-01-07 12:37
543 查看
现在测试下 Java,Linux测试结果如下:
javac test.java
java test
InsertSort total milliseconds:15769
InsertSortWithBinarySerach total milliseconds:15657
程序如下:
Java使用二分插入排序竟然和直接插入排序速度相差不多
之前测试过Python使用二分插入排序竟然比直接插入排序快99倍!现在测试下 Java,Linux测试结果如下:
javac test.java
java test
InsertSort total milliseconds:15769
InsertSortWithBinarySerach total milliseconds:15657
程序如下:
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; } }莫非这两个算法在JVM中运行差别很小?
相关文章推荐
- Java源码-String
- java线程安全
- Java源码-Comparable
- Java控制流程
- Ubuntu 下编译 openJDK
- Java文件IO操作工具类(复制、删除、重命名、创建路径),复制代码并创建FileControl类即可使用。
- Java界面设计 Swing(1)
- 将Maven2项目转为MyEclipse项目
- [spring] 对实体 "characterEncoding" 的引用必须以 ';' 分隔符结尾
- Java集合 Map的遍历
- spring task 配置
- java Fork/join 初探
- Spring事务配置的五种方式
- hashcode方法浅析
- java中文转byte数组
- java集合-Map
- Java 日期格式和String 转换
- java 命令
- JAVA学习【3】对JAVA值传递的理解
- Java HashMap工作原理【图文版】