在这里,我们将看到快速排序技术,但我们将使用三路快速排序。基本的快速排序技术只是找到一个元素作为枢轴,然后围绕枢轴对数组进行分区,之后,在枢轴的左右子数组上递归。
三路快速排序类似,但有三个部分。数组arr[1到n]被分为三个部分。
partition(arr, left, right, i, j) −
begin if right – left <= 1, then if arr[right] < arr[left], then swap arr[right] and arr[left] i := left j := right return end if mid := left, pivot = arr[right] while mid <= right, do if arr[mid] < pivot, then swap arr[left], arr[mid] increase left and mid by 1 else if arr[mid] = pivot, then increase mid by 1 else swap arr[mid], arr[right] decrease right by 1 done i := left – 1 j := mid end
快速排序(arr,左,右) -
begin if left >= right, then return end if define i and j partition(arr, left, right, i, j) quicksort(arr, left, i) quicksort(arr, j, right) end
#include<iostream> #include<vector> using namespace std; void partition(int arr[], int left, int right, int &i, int &j) { if (right - left <= 1) { if (arr[right] < arr[left]) swap(arr[right], arr[left]); i = left; j = right; return; } int mid = left; int pivot = arr[right]; while (mid <= right) { if (arr[mid]<pivot) swap(arr[left++], arr[mid++]); else if (arr[mid]==pivot) mid++; else if (arr[mid] > pivot) swap(arr[mid], arr[right--]); } i = left-1; j = mid; } void quicksort(int arr[], int left, int right) { if (left >= right) //1 or 0 elements return; int i, j; partition(arr, left, right, i, j); quicksort(arr, left, i); quicksort(arr, j, right); } void display(int arr[], int n) { for (int i = 0; i < n; ++i) cout << " " << arr[i]; cout << endl; } int main() { int a[] = {4, 9, 4, 3, 1, 9, 4, 3, 9, 4, 3, 1, 4}; int n = sizeof(a) / sizeof(int); display(a, n); quicksort(a, 0, n - 1); display(a, n); }
4 9 4 3 1 9 4 3 9 4 3 1 4 1 1 3 3 3 4 4 4 4 4 9 9 9
以上是3路快速排序(荷兰国旗问题)的详细内容。更多信息请关注PHP中文网其他相关文章!