插入排序(直接插入排序)

直接插入排序适合数据量不大, 且有序程度高的数据.

 

程序代码:

package ganggong.algorithm.sort;

/**
 * Created by rick on 2015/3/8.
 */
public class InsertionSortTest {
    public static void main(String[] args) {
        InsertionSortTest sortTest = new InsertionSortTest();
        int[] array = {84, 32, 87, 24, 67, 52, 85, 13, 53, 48, 21, 95, 98, 21, 45, 12, 75, 72, 54, 62};
        sortTest.printArray(array);
        System.out.println("begin:");

        sortTest.insertionSort(array);
    }

    private void insertionSort(int[] array) {
        for (int i = 1; i < array.length; i++) {
            for (int j = i; j > 0; j--) {
                if (array[j] < array[j - 1]) {
                    int t = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = t;
                }
            }
            printArray(array);
        }
        assertSorted(array);
    }

    private void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + "\t");
        }
        System.out.println();
    }

    private void assertSorted(int[] array) {
        boolean sorted = true;
        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] > array[i + 1]) {
                sorted = false;
                break;
            }
        }
        if (!sorted) {
            throw new RuntimeException("Not sorted");
        }
    }
}

 

输出结果:

84 32 87 24 67 52 85 13 53 48 21 95 98 21 45 12 75 72 54 62
begin:
32 84 87 24 67 52 85 13 53 48 21 95 98 21 45 12 75 72 54 62
32 84 87 24 67 52 85 13 53 48 21 95 98 21 45 12 75 72 54 62
24 32 84 87 67 52 85 13 53 48 21 95 98 21 45 12 75 72 54 62
24 32 67 84 87 52 85 13 53 48 21 95 98 21 45 12 75 72 54 62
24 32 52 67 84 87 85 13 53 48 21 95 98 21 45 12 75 72 54 62
24 32 52 67 84 85 87 13 53 48 21 95 98 21 45 12 75 72 54 62
13 24 32 52 67 84 85 87 53 48 21 95 98 21 45 12 75 72 54 62
13 24 32 52 53 67 84 85 87 48 21 95 98 21 45 12 75 72 54 62
13 24 32 48 52 53 67 84 85 87 21 95 98 21 45 12 75 72 54 62
13 21 24 32 48 52 53 67 84 85 87 95 98 21 45 12 75 72 54 62
13 21 24 32 48 52 53 67 84 85 87 95 98 21 45 12 75 72 54 62
13 21 24 32 48 52 53 67 84 85 87 95 98 21 45 12 75 72 54 62
13 21 21 24 32 48 52 53 67 84 85 87 95 98 45 12 75 72 54 62
13 21 21 24 32 45 48 52 53 67 84 85 87 95 98 12 75 72 54 62
12 13 21 21 24 32 45 48 52 53 67 84 85 87 95 98 75 72 54 62
12 13 21 21 24 32 45 48 52 53 67 75 84 85 87 95 98 72 54 62
12 13 21 21 24 32 45 48 52 53 67 72 75 84 85 87 95 98 54 62
12 13 21 21 24 32 45 48 52 53 54 67 72 75 84 85 87 95 98 62
12 13 21 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98

 

你可能感兴趣的:(算法,插入排序)