当前位置: 代码迷 >> 综合 >> 算法第一天:插入排序
  详细解决方案

算法第一天:插入排序

热度:35   发布时间:2023-12-29 04:19:56.0
public class Problem04_InsertSort {public static void main(String[] args) {int[] array = {8, 5, 6, 7, 2, 9, 4, 5, 4, 6, 7, 1, 5, 8, 9, 3, 1};printArray(array);insertSort(array);printArray(array);}/**** @author Silent_W* @Description 插入排序* @date 2022/3/8 17:43* @param [array]* @return void*/private static void insertSort(int[] array) {//临界值判断if (array == null || array.length < 2){return;}int N = array.length;//0 ~ 0 完成//0 ~ 1//0 ~ 2//0 ~ N - 1for (int end = 1; end < N; end++){//当前索引位置int newNumIndex = end;//当当前索引位置的左边有值并且左边的值大于当前的值while (newNumIndex - 1 >= 0 && array[newNumIndex - 1] > array[newNumIndex]) {//交换swap(array, newNumIndex,newNumIndex - 1);//当前位置减一newNumIndex --;}}}/**** @author Silent_W* @Description 打印数组* @date 2022/3/8 17:30* @param [array]* @return void*/private static void printArray(int[] array){for (int i = 0; i < array.length; i++) {System.out.print(array[i] + " ");}System.out.println();}/**** @author Silent_W* @Description 交换数组元素* @date 2022/3/8 17:30* @param [array, i, j]* @return void*/private static void swap(int[] array, int i, int j){int temp = array[i];array[i] = array[j];array[j] = temp;}
}

  相关解决方案