快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:經過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的全部數據都比另一部分的全部數據都要小,而後再按此方法對這兩部分數據分別進行快速排序,整個排序過程能夠遞歸進行,以此達到整個數據變成有序序列。算法
算法處理過程(截圖參考 坐在馬桶上看算法:快速排序):ui
代碼:spa
public class QuickSort { public static void sort(int[] arr, int low, int high){ int l = low; int h = high; int tmp = 0; if (l <= h){//掃描低位標小於高位標 tmp = arr[l]; while (l != h){//從兩邊交替掃描,直到l=h while (h>l && arr[h]>tmp) h--; //從右往左掃描,找到第一個比基準數據小的數,進行替換 arr[l] = arr[h]; while (l<h && arr[l]<tmp) l++; //從左往右掃描,找到第一個比基準數據大的數,進行替換 arr[h] = arr[l]; } arr[h] = tmp; sort( arr, low, l-1 ); //對基準元素左邊的數據進行排序 sort( arr, h+1, high ); //對基準元素右邊的數據進行排序 } } public static void main(String[] args){ int[] arr = {10, 2, 1, 7, 12, 23, 32, 4, 6, 98}; sort( arr, 0, arr.length-1 ); for (int i : arr){ System.out.println(i); } } }
時間複雜度:基準數據選擇爲最大或者最小值時,時間複雜度爲O(n^2),若選擇的基準數據爲中間數時,時間複雜度爲O(nlog2n)code
空間複雜度:O(log2n)htm
穩定性:非穩定排序blog
快排應用排序
把一個0-1串(只包含0和1的串)進行排序,你能夠交換任意兩個位置,問最少交換的次數?遞歸
採用快排,左邊的0和右邊的1均可以不用管,只計算須要交換的數據次數便可。get
僞代碼:class
000...10100..1111
int count = 0;
for(int i=0,j=len-1; i<j; ++i,--j){
for(; (i<j)&&(a[i]==0); ++i);
for(; (i<j)&&(a[j]==1); --j);
if(i<j) ++count;
}