上代码:
/**
* 类似插牌,左手为已排序的牌,右手抓牌
* 在左手依次从后向前索引,与右手牌比较
* 右手牌比左手元素小,左手元素向后移一位,比左手元素大,插在左手元素前
*
* @author Administrator
*
*/
public class InsertSort {
public static void insertSort(int[] a){
for(int i = 1;i<a.length;i++){
//x为抓的牌
int x = a[i];
int j = i-1;
//a[j]为左手已排序的牌,自后往前检索,第一次就是a[0]
while(j>=0 && x<a[j]){
a[j+1] = a[j];
j--;
}
//插入x
a[j+1] = x;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {9,34,12,5,6,45,16};
insertSort(a);
for(int i = 0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
}