排序算法之插入排序

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;

public class SortAlgorithms {

    /**
     * 插入排序算法
     * 
     * @param n
     * @return
     */
    static void insertSort(int[] n) {
        for (int j = 1; j < n.length; j++) {
            int k = n[j];
            int i = j - 1;
            while (n[i] > k) {
                n[i + 1] = n[i];
                i--;
                if (i == -1)
                    break;
            }
            n[i + 1] = k;
        }
    }

    /**
     * 插入排序的升序排列
     * 
     * @param n
     * @return
     */
    static void insertSortAscending(int[] n) {
        for (int j = 1; j < n.length; j++) {
            int k = n[j];
            int i = j - 1;
            while (n[i] < k) {
                n[i + 1] = n[i];
                i--;
                if (i == -1)
                    break;
            }
            n[i + 1] = k;
        }
} }
原文地址:https://www.cnblogs.com/xiaojintao/p/3767609.html