插入排序的思想,大家都知道。其实取名为插入排序,倒不如叫做移动排序(个人观点),每次内部循环只需把小的往前移,待到外围循环循环结束时,一定是有序的(有点贪心算法的味道)。
下面是代码实现:
package com.dlut.sort;
import org.junit.Test;
public class InsertSort {
/**
* 插入排序
*/
@Test
public void insertSort_two()
{
int temp = 0,j = 0;
int[] aa= {9,0,1,3,2,5,4,7,6,8,10,23,11,65,23,43};
for (int i = 0; i < aa.length; i++) {
temp = aa[i];
for (j = i; j > 0 && temp < aa[j-1]; j--) {
aa[j] = aa[j-1];
}
aa[j] = temp;
}
for (int i = 0; i < aa.length; i++) {
System.out.println(aa[i]);
}
}
}