插入排序之直接插入排序

package com.sort;

public class InsertSort {//插入排序

	public static void insertSort(int[] a){
		for(int i=1; i<a.length; i++){
			int j = i;
			int key = a[j];//暫存到key中
			while(j>0 && key<a[j-1]){//不斷往後覆蓋
				a[j] = a[j-1];
				j--;
			}
			a[j] = key;//將暫存的key插入
		}
	}
	public static void main(String[] args) {
		int[] a=new int[]{6,5,4,3,2,1};
		insertSort(a);
		for(int array:a){
			System.out.println(array);
		}
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章