public class Suanfa {
final static int COUNT = 500000;
final static int[] array = new int[COUNT];
//初始化数据
static {
Random random = new Random();
for (int i = 0; i < COUNT; i++) {
array[i] = random.nextInt(COUNT * 5);
}
print(array);
System.out.println("..............排序中..............");
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
long h = test(new Hill());
System.out.println("希尔排序 平均时间 " + h);
long i = test(new Insertion());
System.out.println("插入排序 平均时间 " + i);
}
static long test(Sort sort) throws InterruptedException, ExecutionException{
FutureTask<Long> future = new FutureTask<Long>(new SortThread(sort,array));
new Thread(future).start();
return future.get();
}
//排序线程
static class SortThread implements Callable<Long> {
private Sort sort;
private int[] item;
public SortThread(Sort sort,int[] item){
this.sort = sort;
this.item = Arrays.copyOf(item, item.length);
}
public Long call() throws Exception {
long s = System.currentTimeMillis();
int[] ss = sort.get(item);
long e = System.currentTimeMillis();
print(ss);
return e - s;
}
}
//排序接口
interface Sort {
int[] get(int items[]);
}
//希尔排序
static class Hill implements Sort{
public int[] get(int item[]) {
int len = item.length;
int i,j;
int d = len >> 1;
while(d > 0) {
for(i=d;i<len;i++){
j = i-d;
while(j >= 0 && item[j] > item[j+d]){
int temp = item[j];
item[j] = item[j+d];
item[j+d] = temp;
j -= d;
}
}
d = d >> 1;
}
return item;
}
}
//插入排序
static class Insertion implements Sort{
public int[] get(int item[]) {
for (int i = 1; i < item.length; i++) {
if(item[i] < item[i-1]) {
int k = item[i];
int j = i - 1;
item[i] = item[i-1];
while(j > -1 && k < item[j]){
item[j+1]=item[j];
j--;
}
item[j+1] = k;
}
}
return item;
}
}
static void print(int[] items){
/* StringBuffer sb = new StringBuffer();
for (int i = 0; i < items.length; i++) {
sb.append(items[i]).append(",");
}
sb.deleteCharAt(sb.length()-1);
System.out.println(sb);*/
}
}
执行效率
还是希尔排序效率高