本文主要是介绍【经典排序算法 time: 2023-10-12】插入排序(层层优化改进),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
原理
每次循环往后面拿出一个元素排到前面有序序列中(动态演示) -
插排第一版
public class InsertSort {public static void main(String[] args) {long start= System.currentTimeMillis();int[] arr = {11, 23, 69, 99, 1, 3, 45, 67, 5, 234, 678, 999, 7, 123};int[] result = insertSort(arr);System.out.println(Arrays.toString(result));System.out.println(System.currentTimeMillis()-start);}private static int[] insertSort(int[] arr) {for (int i = 1; i < arr.length; i++) {int target = arr[i];for (int j = i-1; j >= 0; j--) {if (target < arr[j]) {swap(arr, j, j+1);}}System.out.println(Arrays.toString(arr));}System.out.println("循环了" +( arr.length -1 ) + "次");return arr;}public static void swap(int[] a, int i, int j) {int t = a[i];a[i] = a[j];a[j] = t;}
}
- 改进一,少去一轮循环,内部循环在找到位置时提前退出,再进行交换
public class InsertSortPlus {public static void main(String[] args) {long start = System.currentTimeMillis();int[] arr = {11, 23, 69, 99, 1, 3, 45, 67, 5, 234, 678, 999, 7, 123};int[] result = insertSort(arr);System.out.println(Arrays.toString(result));System.out.println(System.currentTimeMillis() - start);}private static int[] insertSort(int[] arr) {for (int i = 1; i < arr.length; i++) {int target = arr[i];int j = i - 1;while (j >= 0) {if (arr[j] > target) {arr[j + 1] = arr[j];} else {break;}j--;}arr[j + 1] = target;System.out.println(Arrays.toString(arr));}System.out.println("循环了" + (arr.length - 1) + "次");return arr;}}
这篇关于【经典排序算法 time: 2023-10-12】插入排序(层层优化改进)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!