JAVA-插入排序

插入排序

package com.pb.string.demo1;
/**
 * 插入排序
 * @author Denny
 *
 */
public class Demo {

    public static void main(String[] args) {
        int[] arr = { 5, 2, 8, 3, 1, 9, 6, 7, 11, 0, -3, -5, -8, -11 };
        insertSort(arr);
        print(arr);

    }

    public static void insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i]; // 临时变量存储
            /*for (int j = i - 1; j >= 0 && arr[j] > key; j--) {
                
                arr[j + 1] = arr[j];
                arr[j] = key;
            }*/
            for(int j=i-1;j>=0;j--){
                if(arr[j]>key){
                    //交换变量值
                    arr[j+1]=arr[j]; //当前的下标i的值=当前下标为j的值
                    arr[j]=key;  //
                }
            }
        }

    }

    public static void print(int[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i != arr.length - 1) {
                System.out.print(arr[i] + ",");
            } else {
                System.out.println(arr[i] + "]");
            }
        }
    }

}

结果:

[-11,-8,-5,-3,0,1,2,3,5,6,7,8,9,11]

原文地址:https://www.cnblogs.com/liunanjava/p/4823132.html