现在的位置: 首页 > 综合 > 正文

复习之插入排序

2018年05月26日 ⁄ 综合 ⁄ 共 475字 ⁄ 字号 评论关闭

不多说,看图和代码微笑

package com.lyj.sort.insert;

public class InsertionSort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] array = { 5, 2, 4, 6, 1, 3, 22, 100, 7 };

        // 排序前
        for (int i : array) {
            System.out.print(i + "  ");
        }
        System.out.println();

        // 排序
        insertionSort(array);

        // 排序后
        for (int i : array) {
            System.out.print(i + "  ");
        }

    }

    private static void insertionSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {

            for (int j = i; j >= 0; j--) { // 第二次从后向前依次比较
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }

}

抱歉!评论已关闭.