快速排序之所比較快,因為相比氣泡排序,每次排序的時候設定乙個基準點,將小於等於基準點的數全部放到基準點的左邊,將大於等於基準點的數全部放到基準點的右邊。這樣在每次交換的時候就不會像氣泡排序一樣每次只能在相鄰的數之間進行交換,交換的距離就大的多了。因此總的比較和交換次數就少了,速度自然就提高了。當然在最壞的情況下,仍可能是相鄰的兩個數進行了交換。
快速排序的最差時間複雜度和氣泡排序是一樣的都是o(n2),
平均時間複雜度為o(nlogn)。
快速排序是基於「二分」的思想。
c語言**實現
執行結果#include
#include
#include
#define maxlen 10
void printarray(int arr,int
length)
printf("\n");
}void quicksort(int arr,int left,int right)
if (iwhile (iif (i1);
quicksort(arr, i+1, right);
}else
}int main(int argc, const char * argv)
printf("原始陣列:\n");
printarray(arr, maxlen);
quicksort(arr, 0, maxlen-1);
printf("快排後陣列:\n");
printarray(arr, maxlen);
return
0;}
原始陣列:
4631139
3724
2411
1320
第1輪,left=0,right=9,temp=46203
1139
3724
2411
1320203
1139
3724
2411
1320203
1139
3724
2411
1346
第2輪,left=0,right=8,temp=20133
1139
3724
2411
1346133
1139
3724
2411
3946133
1111
3724
2411
3946133
1111
3724
2437
3946133
1111
3724
2437
3946133
1111
3724
2437
3946133
1111
2024
2437
3946
第3輪,left=0,right=3,temp=13113
1111
2024
2437
3946113
1111
2024
2437
3946113
1113
2024
2437
3946
第4輪,left=0,right=2,temp=11113
1113
2024
2437
3946113
1113
2024
2437
3946113
1113
2024
2437
3946
第5輪,left=0,right=1,temp=1133
1113
2024
2437
394633
1113
2024
2437
3946311
1113
2024
2437
3946
第6輪,left=5,right=8,temp=24311
1113
2024
2437
3946311
1113
2024
2437
3946311
1113
2024
2437
3946
第7輪,left=7,right=8,temp=37311
1113
2024
2437
3946311
1113
2024
2437
3946311
1113
2024
2437
3946
快排後陣列:
3111113
2024
2437
3946
program ended with
exit code: 0
演算法 快速排序的實現
理解 快速排序對問題分而治之的一種方法,在每一趟排序後,都能確定乙個數的位置 即分割點 因此快速排序的核心是確定分割點的位置並把陣列按大小分在分割點的兩側。因此快排可以分為兩部分,第一部分是遞迴處理問題,第二部分是找到分割點 第一部分 def quicksort l,r if l r return ...
快速排序演算法實現
快速排序演算法的原理 將數列中任取乙個數,將其左部放置比其小的數,其右部放置比其大的數。然後,對其左,右部遞迴執行這種分割過程。原始碼如下 int32 sorteddata int32 quicksort int32 sortdata,dword sortdatalen assert sortdat...
快速排序演算法實現
學完了快速排序演算法,感覺挺容易的,所以趁著有點時間就寫了個實現程式。採用了介面和實現分離的原則 qsort.h inte ce of the quick sort define num 2000 設定最多個數為1999個 class qsort qsort.cpp include qsort.h ...