經典排序之插入排序

插入排序的思想很簡單,就是每向有序序列中插入一個數,就把這個數依次與其他數比較,逐次替換。

下面是代碼

public class InsertSort {
    
	public void insertSort(int a[]){
    	int length=a.length;
    	int i;
    	int keyword;
    	for(int j=1;j<length;j++){
    		keyword=a[j];
    		i=j-1;
    		while(i>=0 && a[i]>keyword){
    			a[i+1]=a[i];
    			i--;
    		}
    		a[i+1]=keyword;
    		System.out.println(Arrays.toString(a));
    	}
    }
	
	public static void main(String[] args){
		int a[]={6,3,4,2,1,5};
		InsertSort insertSort=new InsertSort();
		insertSort.insertSort(a);
		/*for(int i=0;i<a.length;i++){
			System.out.println(a[i]);
		}*/
		
		/*Random random=new Random();
		int[] a=new int[10000];
		for(int i=0;i<a.length;i++){
			a[i]=random.nextInt(10000);
		}

		InsertSort insertSort=new InsertSort();
		long startTime=System.currentTimeMillis();
		insertSort.insertSort(a);
		long endTime=System.currentTimeMillis(); 
	    System.out.println("程序運行時間: "+(endTime-startTime)+"ms");
	    for(int i=0;i<a.length;i++){
			System.out.println(a[i]);
		}*/
	}
}
代碼很簡單,我就不多說什麼了。

下面是序列

[3, 6, 4, 2, 1, 5]
[3, 4, 6, 2, 1, 5]
[2, 3, 4, 6, 1, 5]
[1, 2, 3, 4, 6, 5]
[1, 2, 3, 4, 5, 6]


發佈了39 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章