public class code_select { // 插入排序 public static void insertSort(int [] arr){ if(arr == null || arr.length < 2){ return; } int N = arr.length; for (int end = 1; end < N; end++) { int newNumIndex = end; while (newNumIndex - 1 >= 0 && arr[newNumIndex - 1] > arr[newNumIndex]){ swap(arr, newNumIndex-1, newNumIndex); newNumIndex--; } } } public static void insertSort2(int [] arr){ // 边界值检查 if(arr == null || arr.length < 2){ return; } int N = arr.length; for (int end = 1 ; end < N; end ++){ for (int pre = end - 1 ; pre >= 0 && arr[pre] > arr[pre + 1]; pre -- ){ swap(arr, pre, pre + 1); } } } public static void swap(int[] arr, int i , int j){ int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } public static void printArray(int [] arr){ for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void main(String[] args) { int[] arr = {7, 1, 2, 3, 5, 8}; printArray(arr); insertSort(arr); printArray(arr); }}