import java.util.*; public class InsertionSort { /* * 升序排列 * * */ public static void insertSort(int[] input) { for (int i = 1; i < input.length; i++) { int key = input[i]; int j = i - 1; while (j >= 0 && input[j] > key) { input[j + 1] = input[j]; j = j - 1; } // 每次右移后,j 都要左移,所以要+ 1 j = j + 1; input[j] = key; } } public static void main(String[] args) { // int[] input = { 1, 3, 7, 6, 4, 2, 9, 0 }; int len = 10; int [] input = new int [len]; Random random = new Random(); for(int i = 0; i < len; i ++) { input[i] = random.nextInt(1000); } insertSort(input); for (int i = 0; i < input.length; i++) { System.out.print(input[i] + " "); } } }