快速排序算法

快速排序每次自己寫都寫不出來,這回下決心每天練習一回,並且先把寫好的在博客中記錄一下,方便回憶

int arr[] = new int[]{38, 8, 6, 12, 88, 44, 98, 41, 38, 78, 66, 77, 33, 55, 99, 44, 55, 22, 77};


System.out.println();

for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + "\t");
}

fun4(arr, 0, arr.length - 1);

System.out.println();

for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + "\t");
}

System.out.println();

System.out.println("count = " + count);
    // 快速排序
    public static void fun4(int arr[], int start, int end) {

        if (start >= end) {
            return;
        }

        int keyIndex = start;
        int key = arr[keyIndex];

        int startIndex = start + 1;

        for (int i = end; i >=startIndex;) {
            if (arr[i] < key) {
                int tmp = arr[startIndex];
                arr[startIndex] = arr[i];
                arr[i] = tmp;
                startIndex++;
            }else{
                i--;
            }
        }

        arr[keyIndex] = arr[startIndex - 1];
        arr[startIndex - 1] = key;

        fun4(arr, start, startIndex - 1);

        fun4(arr, startIndex, end);

    }
    // 快速排序
    public static void fun5(int arr[], int start, int end) {

        if (start >= end) {
            return;
        }

        int keyIndex = start;
        int key = arr[keyIndex];

        int startIndex = start + 1;

        for (int i = startIndex; i <= end; i++) {
            if (arr[i] < key && i != startIndex) {
                int tmp = arr[startIndex];
                arr[startIndex] = arr[i];
                arr[i] = tmp;
                startIndex++;
            }
        }
        arr[keyIndex] = arr[startIndex - 1];
        arr[startIndex - 1] = key;

        fun4(arr, start, startIndex - 1);

        fun4(arr, startIndex, end);

    }
    public static void fun6(int arr[], int start, int end) {

        if (start >= end) {
            return;
        }

        int keyIndex = start;
        int key = arr[keyIndex];

        int startIndex = start;
        int endIndex = end;

        while (endIndex > startIndex) {

            while (arr[endIndex] >= key && endIndex > startIndex)
                endIndex--;

            while (arr[startIndex] <= key && endIndex > startIndex)
                startIndex++;

            if (endIndex > startIndex) {
                int tmp = arr[startIndex];
                arr[startIndex] = arr[endIndex];
                arr[endIndex] = tmp;
            }

        }

        arr[keyIndex] = arr[startIndex];
        arr[startIndex] = key;

        fun6(arr, start, startIndex - 1);

        fun6(arr, startIndex + 1, end);

    }
發佈了119 篇原創文章 · 獲贊 275 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章