从小到大插入排序

来源:互联网 发布:李艺彤总选 知乎 编辑:程序博客网 时间:2024/06/02 19:18
插入排序的基本思想就是把元素分为已排序和未排序两部分, 依次取出未排序部分的元素插入排序部分中
public class Insertion_Sort {    public static void main(String[] args) {        // 待排序序列        int[] nums = {1, 6, 3, 8, 12, 9, 7};        // 从序列第二个数开始, 之前的序列都是已排序序列        for (int i =  1; i < nums.length; i++){            int key = nums[i];            int j = i - 1;            // 从当前元素往前查找插入位, 因为之前的数都是已排序序列, 所以如果前面的数大于待插入数,则前面的数依次往后移位。直到小于或等于它的元素            while(j >= 0 && key < nums[j]){                nums[j+1] = nums[j];                j--;            }            nums[j+1] = key;            // 输出每次排序之后的结果            for (Integer num : nums) {                System.out.print(num + " ");            }            System.out.println();        }    }}