插入排序
/**
* 插入排序
*/
public static int[] insertionSort(int[] array) {
int temp = 0;
for (int i = 1; i < array.length; i++) {
int j = i - 1;
temp = array[i];
for (; j >= 0 && temp < array[j]; j--) {
array[j + 1] = array[j];
}
array[j + 1] = temp;
}
return array;
}
运行
/**
* 待排序的数组
*/
private static int[] array = {
12, 10, 5, 9, 5, 32, 16, 1, 9, 99, 80, 3, 18, 19, 20, 25, 7, 15
};
public static void main(String[] args) {
int[] result = SortUtils.insertionSort(array.clone());
System.out.println(Arrays.toString(result));
}
输出
[1, 3, 5, 5, 7, 9, 9, 10, 12, 15, 16, 18, 19, 20, 25, 32, 80, 99]