2020-04-27 10:07:10 +08:00
|
|
|
import java.util.Arrays;
|
2020-04-26 20:16:26 +08:00
|
|
|
|
2020-04-27 10:07:10 +08:00
|
|
|
public class InsertionSort {
|
2020-07-22 20:36:54 +08:00
|
|
|
|
2020-04-27 10:07:10 +08:00
|
|
|
private static void insertionSort(int[] nums) {
|
2020-07-22 20:36:54 +08:00
|
|
|
for (int i = 1, j, n = nums.length; i < n; ++i) {
|
|
|
|
|
int num = nums[i];
|
2022-09-05 23:58:38 +08:00
|
|
|
for (j = i - 1; j >= 0 && nums[j] > num; --j) {
|
2020-04-26 20:16:26 +08:00
|
|
|
nums[j + 1] = nums[j];
|
|
|
|
|
}
|
2020-07-22 20:36:54 +08:00
|
|
|
nums[j + 1] = num;
|
2020-04-26 20:16:26 +08:00
|
|
|
}
|
|
|
|
|
}
|
2020-07-22 20:36:54 +08:00
|
|
|
|
2020-04-27 10:07:10 +08:00
|
|
|
public static void main(String[] args) {
|
2020-07-22 20:36:54 +08:00
|
|
|
int[] nums = {1, 2, 7, 9, 5, 8};
|
2020-04-27 10:07:10 +08:00
|
|
|
insertionSort(nums);
|
|
|
|
|
System.out.println(Arrays.toString(nums));
|
|
|
|
|
}
|
2020-07-22 20:36:54 +08:00
|
|
|
}
|