天天看點

【資料結構與算法】插入排序

記錄一下插入排序。

public class InsertionSort {

    public static void sort(Integer[] array) {
        if (array == null || array.length == 0) {
            return;
        }

        Integer value = null;
        Integer tempIndex = null;
        for (int i = 1; i < array.length; i++) {
            value = array[i];
            tempIndex = i - 1;

            while (tempIndex >= 0) {
                if (value < array[tempIndex]) {
                    /* 周遊有序序列,遇到比要插入的元素大的元素,則後移一位 */
                    array[tempIndex + 1] = array[tempIndex];
                    tempIndex--;
                } else {
                    /* 周遊有序序列,遇到比要插入的元素小的元素,可以停止了 */
                    break;
                }
            }

            array[tempIndex + 1] = value;
        }
    }

}      
import org.junit.Test;


public class HowToTest {

    @Test
    public void c1() {
        Integer[] array = {3,16,1,5,2,18,0,9,20,11};
        InsertionSort.sort(array);

        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + ", ");
        }
        System.out.println();
    }

    @Test
    public void c2() {
        Integer[] array = {99,98,97,96,95,94,93,92,91,101,90,89,88,87,86,85};
        InsertionSort.sort(array);

        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + ", ");
        }
        System.out.println();
    }

}      

作者:Nick Huang 部落格:http://www.cnblogs.com/nick-huang/

本部落格為學習、筆記之用,以筆記形式記錄學習的知識與感悟。學習過程中可能參考各種資料,如覺文中表述過分引用,請務必告知,以便迅速處理。如有錯漏,不吝賜教。

如果本文對您有用,

點贊

評論

哦;如果您喜歡我的文章,請點選

關注我

哦~

繼續閱讀