基本原理
插入排序(英语:Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
动态图
代码(这个地方用的是前后交换的方式)
package com.qcby; import java.util.Arrays; public class Shu { public static void main(String[] args) { int[] arr = new int[] {6,5,3 ,1,8,7,2,4}; Sort(arr); } public static void Sort(int[] arr) { for (int i = 1; i < arr.length; i++) { //将当前数据插入到已经有序的数字当中(这里需要倒着往前找) for ( int j = i-1; j >= 0; j--) { //前后位置进行交换 if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; }else { break; } } System.out.println(Arrays.toString(arr)); } } }
输出结果如下:
[5, 6, 3, 1, 8, 7, 2, 4] [3, 5, 6, 1, 8, 7, 2, 4] [1, 3, 5, 6, 8, 7, 2, 4] [1, 3, 5, 6, 8, 7, 2, 4] [1, 3, 5, 6, 7, 8, 2, 4] [1, 2, 3, 5, 6, 7, 8, 4] [1, 2, 3, 4, 5, 6, 7, 8]
代码(移位方式)
package com.qcby; import java.util.Arrays; public class Shu { public static void main(String[] args) { int[] arr = {-1,100,4,23,2,45,67,89,-3,56}; System.out.print("排序前:"); System.out.println(Arrays.toString(arr)); insertSort(arr); } //直接插入排序(移位方式) public static void insertSort(int[] arr){ for(int i=1;i<arr.length;i++){ int insertVal = arr[i]; int insertIndex = i; while (insertIndex>0 && insertVal<arr[insertIndex-1]){ arr[insertIndex]=arr[insertIndex-1]; insertIndex--; } arr[insertIndex] = insertVal; //输出每趟的结果 System.out.print("第" + i + "轮:"); System.out.println(Arrays.toString(arr)); } //排序完成后输出最终的结果 System.out.println("=================================================="); System.out.println(Arrays.toString(arr)); } }
输出结果如下:
排序前:[-1, 100, 4, 23, 2, 45, 67, 89, -3, 56] 第1轮:[-1, 100, 4, 23, 2, 45, 67, 89, -3, 56] 第2轮:[-1, 4, 100, 23, 2, 45, 67, 89, -3, 56] 第3轮:[-1, 4, 23, 100, 2, 45, 67, 89, -3, 56] 第4轮:[-1, 2, 4, 23, 100, 45, 67, 89, -3, 56] 第5轮:[-1, 2, 4, 23, 45, 100, 67, 89, -3, 56] 第6轮:[-1, 2, 4, 23, 45, 67, 100, 89, -3, 56] 第7轮:[-1, 2, 4, 23, 45, 67, 89, 100, -3, 56] 第8轮:[-3, -1, 2, 4, 23, 45, 67, 89, 100, 56] 第9轮:[-3, -1, 2, 4, 23, 45, 56, 67, 89, 100] ================================================== [-3, -1, 2, 4, 23, 45, 56, 67, 89, 100]