最简单的排序算法——插入排序。代码中有计算排序耗费时间的计算countTime(),以毫秒计算排序过程花费了多长时间。
// ArgDemo1.java
import java.util.*;
public class ArgDemo1 {
public static void printArray(int[] ary) {
for (int i=0; i<ary.length; i++){
if (i%10 == 0) System.out.println();
System.out.print(ary[i]+"\t");
}
System.out.println();
}
public static long countTime(){
java.util.Calendar c = java.util.Calendar.getInstance();
return (c.getTimeInMillis());
}
public static void InsertSort(int[] a)
{
int key=0;
int i=0;
int j=0;
//System.out.println("===Starting Insert sort===");
for(j=1; j<a.length; j++) {
key = a[j];
i = j-1;
//System.out.println("key= "+key);
while(i>=0 && a[i]>key){
//System.out.println("key= "+key);
a[i+1] = a[i];
i--;
//printArray(a);
}
a[i+1] = key;
}
//System.out.println("===End Insert sort===");
}
public static void main(String[] arg) {
int N = 10;
int [] arryTemp = new int[N];
long time = 0;
System.out.println("------Random Array-------");
for (int i=0; i<N; i++){
Random rand = new Random();
arryTemp[i]=rand.nextInt(N);
}
printArray(arryTemp);
// sort Array
time = countTime();
InsertSort(arryTemp);
time = countTime() - time;
System.out.println("\n------Sorted Array-------");
printArray(arryTemp);
System.out.println("\nSort time: "+time+" Millions Second.");
}
}
// Output EX.:
//------Random Array-------
//
//0 2 8 1 5 1 5 2 6 4
//
//------Sorted Array-------
//
//0 1 1 2 2 4 5 5 6 8
//
//Sort time: 0 Millions Second.
//~