InsertSort java 实现


最简单的排序算法——插入排序。代码中有计算排序耗费时间的计算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.
//~




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值