java快速排序

來源:互聯網
上載者:User

標籤:快速排序   擴充   nbsp   ++   str   冒泡   lin   分數   最好   

快速排序:對冒泡排序的一種改進,若初始記錄序列按關鍵字有序或基本有序,蛻化為冒泡排序。使用的是遞迴原理,在所有同數量級O(n longn) 的排序方法中,其平均效能最好。就平均時間而言,是目前被認為最好的一種內部排序演算法;

基本思想:通過一躺排序將要排序的資料分割成獨立的兩部分,其中一部分的所有資料都比另外一部分的所有資料都要小,然後再按此方法對這兩部分資料分別進行快速排序,整個排序過程可以遞迴進行,以此達到整個資料變成有序序列。

三個指標: 第一個指標稱為pivotkey指標(樞軸),第二個指標和第三個指標分別為left指標和right指標,分別指向最左邊的值和最右邊的值。left指標和right指標從兩邊同時向中間逼近,在逼近的過程中不停的與樞軸比較,將比樞軸小的元素移到低端,將比樞軸大的元素移到高端,樞軸選定後永遠不變,最終在中間,前小後大;

代碼如下:

 1 public class QuickSort {   2     public static void main(String[] args) {   3         int[] array = { 1, 2, 4, 6, 3, 0, 5 };   4         quickSort(array, 0, array.length - 1);   5         for (int i = 0; i < array.length; i++) {   6             System.out.print(array[i] + " -- ");   7         }   8     }   9   10     /** 11      * 先按照數組為資料原型寫出演算法,再寫出擴充性演算法。數組{49,38,65,97,76,13,27} 12      * 遞迴函式 13      * @param array 14      * @param left 15      * @param right 16      */  17     public static void quickSort(int[] array, int left, int right) {  18         int pivotKey;  19         if (left < right) {  20             pivotKey = partitionByPivotValue(array, left, right);  21             // 對左右數組遞迴調用快速排序,直到順序完全正確  22             quickSort(array, left, pivotKey - 1);  23             quickSort(array, pivotKey + 1, right);  24         }  25     }  26   27     /** 28      * pivotValue作為樞軸,較之小的元素排序後在其左,較之大的元素排序後在其右 29      *  分割函數30      * @param array 31      * @param left 32      * @param right 33      * @return 34      */  35     public static int partitionByPivotValue(int[] array, int left, int right) {  36         int pivotValue = array[left];  37         // 樞軸選定後永遠不變,最終在中間,前小後大  38         while (left < right) {  39             while (left < right && array[right] >= pivotValue) {  40                 --right;  41             }  42             // 將比樞軸小的元素移到低端,此時right位相當於空,等待低位比pivotkey大的數補上  43             array[left] = array[right];  44             while (left < right && array[left] <= pivotValue) {  45                 ++left;  46             }  47             // 將比樞軸大的元素移到高端,此時left位相當於空,等待高位比pivotkey小的數補上  48             array[right] = array[left];  49         }  50         // 當left == right,完成一趟快速排序,此時left位相當於空,等待pivotkey補上  51         array[left] = pivotValue;  52         return left;  53     }  54 }

 

java快速排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.