插入排序

package alg;

import java.util.Arrays;

/**
 * 插入排序
 * Created by dinghaiyun on 2017/9/1.
 */
public class InsertionSort {
    public static void main(String[] args) {
        int[] arr = {5, 1, 3, 6, 7, 8, 2};
        sort(arr);
        System.out.println("insert sort result: " + Arrays.toString(arr));
    }

    private static void sort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int current = arr[i];
            int j = i - 1;

            while (j >= 0 && arr[j] > current) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = current;
        }
    }
}

 

posted @ 2017-09-04 18:08  冰河世纪-dhy  阅读(101)  评论(0编辑  收藏  举报