快速排序的代碼實現


package com.Summer_0422.cn;
import java.util.Arrays;

public class Test07 {
    public static void main(String[] args) {
        int[] array = getArray(); //生成一個有10個元素的隨機數組
        quickSort(array,0,array.length-1);// 調用快速排序的方法
        System.out.println(Arrays.toString(array)); //顯示快排結果
        
    }

    private static void quickSort(int[] array, int leftBound, int rightBound) {
        if (leftBound >rightBound) { // 確定好排序范圍,否則會報數組越界異常
            return;
        }
        int i = leftBound; // 定義數組最左側的浮標i
        int j = rightBound;  // 定義數組最右側的浮標j
        int pivot = array[leftBound]; // 聲明一個pivot作為基准數  ,將數組最左邊的元素賦給這個基准數
        while (i != j) { // 如果兩個浮標i和j不相等的情況下
            while (i<j && array[j] >= pivot) {  //始終注意不要引起數組索引越界,如果array[j] 大於等於基准數,array[j]上的值保持不動,但浮標j向左移一位
                j--; //浮標j左移
            }
            while (i<j && array[i] <= pivot) {//始終注意不要引起數組索引越界,如果array[i] 小於等於基准數,array[i]上的值保持不動,但浮標i向左移一位
                i++; //同理浮標i右移
            }
            swap(array, i, j); //此時交換i和j索引上的數據
        }
        //程序可以來到這里說明i和j此時相等
        //將此時浮標i或j上的數值和基准數進行交換,至此找到了中間的基准索引
        swap(array, leftBound, i);
        //以基准索引作為邊界,兩側分別進行遞歸操作即可
        //比基准小的重新進行排序
        quickSort(array, leftBound, i-1);
        // 比基准大的重新進行排序
        quickSort(array, i+1, rightBound);
    
    }
    // 獲取一個范圍在1-100內的有10個元素的數組
    public static int[] getArray() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int)(Math.random()*100+1);
        }
        System.out.println("系統自動生成的數組是:"+Arrays.toString(arr));
        return arr;
    }
    // 這是用於交換的方法
    public static void swap(int[] array, int x, int y) {
        int temp = array[x]; //數組中的第x上的元素賦值給temp
        array[x] = array[y];
        array[y] =temp;
        

            
        }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM