插入排序算法:数组长度为N,共遍历P=(1到N-1)次,每次遍历下标<=P的数字已按大小排序。
| 32,23,54,43,74,66,94,86
P=1| 23,32,54,43,74,66,94,86
P=2| 23,32,54,43,74,66,94,86
P=3| 23,32,43,54,74,66,94,86
P=4| 23,32,43,54,74,66,94,86
P=5| 23,32,43,54,66,74,94,86
P=6| 23,32,43,54,66,74,94,86
P=7| 23,32,43,54,66,74,86,94
java实现如下:
public class NumSortTest {
public void numSort(int[] numArray){
for(int i = 1; i < numArray.length; i ++){
for(int j = i; j > 0; j --){
if(numArray[j] < numArray[j-1]){
int temp = numArray[j];
numArray[j] = numArray[j-1];
numArray[j-1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] numArray = new int[]{32,23,54,43,74,66,94,86};
new NumSortTest().numSort(numArray);
for(int i = 0; i < numArray.length; i ++){
System.out.print(numArray[i]+" ");
}
}
}
结果:
23 32 43 54 66 74 86 94