1. 程式人生 > 其它 >快速排序演算法-java

快速排序演算法-java

快速排序演算法通過多次比較和交換來實現排序,其排序流程如下:

1.首先設定一個分界值,通過該分界值將陣列分成左右兩部分。

2.將大於或等於分界值的資料集中到陣列右邊,小於分界值的資料集中到陣列的左邊。此時,左邊部分中各元素都小於或等於分界值,而右邊部分中各元素都大於或等於分界值。

3.然後,左邊和右邊的資料可以獨立排序。對於左側的陣列資料,又可以取一個分界值,將該部分資料分成左右兩部分,同樣在左邊放置較小值,右邊放置較大值。右側的陣列資料也可以做類似處理。

4.重複上述過程,可以看出,這是一個遞迴定義。通過遞迴將左側部分排好序後,再遞迴排好右側部分的順序。當左、右兩個部分各資料排序完成後,整個陣列的排序也就完成了。

import org.junit.Test;

public class QuickSort {
    public void quick_sort(int[] array, int leftIndex, int rightIndex) {
        if (leftIndex >= rightIndex) {
            return;
        }
        if (leftIndex < rightIndex) {
            int left = leftIndex;
            int right = rightIndex;
            
int x = array[left]; while (left < right) { while ((left < right) && (array[right] >= x)) { right--; } if (left < right) { array[left] = array[right]; }
while ((left < right) && (array[left] <= x)) { left++; } if(left<right){ array[right] = array[left]; } } array[left] = x; quick_sort(array, leftIndex, left - 1); quick_sort(array, left + 1, rightIndex); } } @Test public void fun1() { int[] a = {7, 10, 5, 3, 6, 8, 4, 9, 1, 2}; System.out.println("快速排序前的陣列為:"); for (int b : a) { System.out.print(b + " "); } System.out.println(""); quick_sort(a, 0, a.length - 1); System.out.println("快速排序後的陣列為:"); for (int b : a) { System.out.print(b + " "); } } }

詳細排序演算法原理介紹參考:https://www.cnblogs.com/skywang12345/p/3596746.html