插入排序:
基本思想:假设前面(n-1)[n>=2]个数已经排好,现在要把第n个数插到前面有序数中。反复循环。
/** * 插入排序 * @author Ant * */
public class InsertSort {
/** * 基本思想:假设前面(n-1)[n>=2]个数已经排好,现在要把第n个数插到前面有序数中。反复循环 * @param a * @return */
public static void insertSort(int[] a){
int temp = 0;//存储第n个数
//循环从1开始
for(int i = 1; i < a.length; i++){
int j = i-1;
temp = a[i];//存第N个数
//当j>=0 且 前面的数大于temp,把前面的数往后挪一位
for(; j >= 0 && a[j] > temp; j--){
a[j+1]=a[j];
}
a[j+1]=temp;//最后把第N个数插入到合适的位置。
}
}
public static void main(String[] args) {
int a [] = {38, 24, 10, 3, 5, 18};
InsertSort.insertSort(a);
for(int i = 0; i < a.length; i++){
System.out.println(a[i]+" ");
}
}
}