首页 > 其他分享 >InsertionSort

InsertionSort

时间:2023-11-19 10:56:50浏览次数:38  
标签:index int InsertionSort mark cursor insertionSort array

 

Java

    private static void insertionSort(int[] array) {
        for (int i = 1; i < array.length; ++i) {
            int index = i - 1, mark = array[i];
            while (mark < array[index]) {
                array[index + 1] = array[index];
                index--;
                if (index == -1) {
                    break;
                }
            }
            array[index + 1] = mark;
        }
    }

 

    private static void insertionSort(int[] array) {
        int index, mark;
        for (int i = 1; i < array.length; i++) {
            index = i - 1;
            mark = array[i];
            while (index >= 0) {
                if (array[index] > mark) {
                    array[index + 1] = array[index];
                } else {
                    // array[index + 1] = mark;
                    // wrong, when mark is the minimum, array[index+1] = mark; is not executed
                    break;
                }
                index--;
            }
            array[index + 1] = mark;
        }
    }

 

    private static void insertionSort(int[] array) {
        int cursor, key;
        for (int i = 1; i < array.length; ++i) {
            key = array[i];
            for (cursor = i - 1; cursor >= 0; --cursor) {
                if (array[cursor] <= key) {
                    break;
                }
                array[cursor + 1] = array[cursor];
            }
            array[cursor + 1] = key;
        }
    }

 

标签:index,int,InsertionSort,mark,cursor,insertionSort,array
From: https://www.cnblogs.com/dissipate/p/17841715.html

相关文章

  • InsertionSort2
    [ARC162B]InsertionSort2本题还是对于不变量的考察,但是比较明显。首先两个数捆绑插到任意一个位置可以等价为偶数次相邻交换((因为你每次可以这样:比如现在是a<b<c,a,b,c,你可以交换a,c,变为c,b,a,然后交换ab,变为c,a,b,这样你就会往后挪动一次,往前同理①)。然后我们知道每次相邻......