public class InsertSort {
public static void swap(int[] array, int i, int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
/**排序*/
public static void insertSort(int[] array) {
//首先考虑边界条件
if(array == null || array.length < 2) {
return;
}
//打扑克牌 手上拿125,来个4,逐个往左比较,插到合适的位置
for (int i = 1; i < array.length; i ++) {
int newValueIndex = i;
while(newValueIndex - 1 >= 0 && array[newValueIndex] < array[newValueIndex - 1]) {
swap(array,newValueIndex-1,newValueIndex);
newValueIndex --;
}
}
}
public static void main(String[] args) {
//给定一个数组
int[] array = {5,7,1,3,23,22,53,21,4,66,68,124,8};
PrintUtil.printIntArray(array); //5 7 1 3 23 22 53 21 4 66 68 124 8
insertSort(array);
PrintUtil.printIntArray(array); //1 3 4 5 7 8 21 22 23 53 66 68 124
}
}
标签:int,插入排序,public,static,66,newValueIndex,array
From: https://www.cnblogs.com/xinay/p/16848865.html