排序 (2)快速排序
生活随笔
收集整理的這篇文章主要介紹了
排序 (2)快速排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 思想
step1. 從數列中挑出一個元素,稱為 “基準”(pivot)。
step2. 分區(partition):重新排序數列,所有元素比基準值小的擺放在基準前面,所有元素比基準值大的擺在基準的后面(相同的數可以到任一邊)。
step3. 遞歸地(recursive)把基準值左邊的子數列和右邊的子數列排序。
1.1 具體實現
step1. 以最左邊為基準值,將a[low]作為pivot
step2. j值開始是low+1,i從j開始循環,將j指向當前第一個比pivot大的值,如果發現數組中有一個比pivot小,就將a[i]與a[j]替換
step3. 循環結束,此時a[low]是pivot,a[low+1]到a[j-1]的值都小于pivot,j右邊的值都大于pivot。將a[low]與a[j-1]互換
1.2 圖示
遞歸:
1.3 code
void swap(int& a, int& b){int t = a;a = b;b = t;}int partition(int arr[], int low, int high){int pivot = arr[low]; // pivotint j = low+1; // Index of smaller element and indicates the right position of pivot found so farfor (int i = j; i <= high; i++){// If current element is smaller than the pivotif (arr[i] < pivot){swap(arr[j], arr[i]);j++; // increment index of smaller element}}swap(arr[j-1], arr[low]);return (j-1);}void quickSort(int A[], int low, int high) //快排母函數{if (low < high) {int pivot = partition(A, low, high);quickSort(A, low, pivot - 1);quickSort(A, pivot + 1, high);}}void test() { int a[] = { 1, 4, 5, 2, 10, 8 };int nSize = sizeof(a) / sizeof(int);quickSort(a, 0, nSize-1);}eg.
數組: 4 2 5 3 10 pivot: 4開始: 4 2 5 3 10j-> 4 2 5 3 10j -> 4 2 3 5 10j循環結束:再將a[low] 與a[j-1]互換-> 3 2 4 5 10【引用】
[1] 代碼quickSort.h
總結
以上是生活随笔為你收集整理的排序 (2)快速排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Boost Asio总结(15)clas
- 下一篇: 排序 (4)插入排序