常用排序算法3

插入排序1:

public static void main(String[] args) {
        int[] array = new int[] { 3, -4, 39, 2, 5, 7, 1, 8, 0, 12, 2 };
        insertionSort(array);
        for(int x : array) {
            System.out.print(x + "  ");
        }
    }
    public static void insertionSort(int[] arr) {
        int len = arr.length;
        int preIndex, current;
        for (int i = 1; i < len; i++) {
            preIndex = i - 1;
            current = arr[i];
            while (preIndex >= 0 && arr[preIndex] > current) {
                arr[preIndex + 1] = arr[preIndex];
                preIndex--;
            }
            arr[preIndex + 1] = current;
        }
    }

插入排序2:

public static void main(String args[]) {
        int[] array = new int[] { 3, -4, 39, 2, 5, 7, 1, 8, 0, 12, 2 };
        for(int x : array) {
            System.out.print(x + "  ");
        }
        System.out.println();
        for(int i = 1;i<array.length;i++) {
            int x = array[i];
            for(int j = 0;j<i;j++) {
                if(x>array[j]) {
                    for(int k = i-1;k>=j;k--) {
                        array[k+1] = array[k];
                    }
                    array[j] = x;
                    break;
                }
            }
        }
        
        for(int x : array) {
            System.out.print(x + "  ");
        }
    }

猜你喜欢

转载自blog.csdn.net/goJiaWei123/article/details/86687490