算法思想:把n个待排序的元素看成为一个有序表和一个无序表,开始时有序表中只包含一个元素,无序表中包n-1个元素,排序过程中每次从无序表中取出一个元素,把他的元素依次与有序表的元素进行比 较,将它插入到有序表中的适当位置,使之成为新的有序表。
每次在颜色较浅的无序序列里,选择一个元素,放入有序序列的合适位置,直到序列全部有序。
代码如下:
import java.util.Arrays; public class InsertSort { public static void main(String[] args) { int[] arr = {17,3,25,14,20,9}; inertSort(arr); System.out.println(Arrays.toString(arr)); } //插入排序 public static void inertSort(int[] arr){ for (int i = 1; i < arr.length; i++) { int insertValue = arr[i]; //记录无序的第一个值 int index = i - 1; //有序的最后一个值的下标 while(index >= 0 && insertValue < arr[index]){//无序的第一个数值比有序的最后一个值还要小,说明没有在合适的位置 arr[index + 1] = arr[index]; //值后移 index --; } //退出该循环说明找到了合适的位置 arr[index + 1] = insertValue; } } }