时间复杂度: 最差情况
O
(
n
2
)
O(n^2)
O(n2) ,最好情况
O
(
n
log
2
n
)
O(n\log_2n)
O(nlog2n)
// [l,r]
int partition(vector<int>& nums,int l,int r){
// select nums[r] as pivot
int pivot = nums[r];
int j = l-1;
for(int i = l; i < r;++i){
if(nums[i] < pivot){
j++;
std::swap(nums[j],nums[i]);
}
}
j++;
std::swap(nums[j],nums[r]);
return j;
}
void quick_sort(vector<int>&nums,int l,int r){
if(l >= r) return;
int j = partition(nums,l,r);
quick_sort(nums,l,j-1);
quick_sort(nums,j+1,r);
}
3-Way QuickSort
在3-Way QuickSort中,数组被分为3部分:
arr[l … i] : 元素都小于pivot
arr[i+1 … j-1] 元素都等于pivot
arr[j … r] 元素都大于pivot
/* This function partitions a[] in three parts
a) a[l..i] contains all elements smaller than pivot
b) a[i+1..j-1] contains all occurrences of pivot
c) a[j..r] contains all elements greater than pivot */
void partition(int a[], int l, int r, int &i, int &j)
{
i = l-1, j = r;
int p = l-1, q = r;
int v = a[r];
while (true)
{
// From left, find the first element greater than
// or equal to v. This loop will definitely terminate
// as v is last element
while (a[++i] < v);
// From right, find the first element smaller than or
// equal to v
while (v < a[--j])
if (j == l)
break;
// If i and j cross, then we are done
if (i >= j) break;
// Swap, so that smaller goes on left greater goes on right
swap(a[i], a[j]);
// Move all same left occurrence of pivot to beginning of
// array and keep count using p
if (a[i] == v)
{
p++;
swap(a[p], a[i]);
}
// Move all same right occurrence of pivot to end of array
// and keep count using q
if (a[j] == v)
{
q--;
swap(a[j], a[q]);
}
}
// Move pivot element to its correct index
swap(a[i], a[r]);
// Move all left same occurrences from beginning
// to adjacent to arr[i]
j = i-1;
for (int k = l; k < p; k++, j--)
swap(a[k], a[j]);
// Move all right same occurrences from end
// to adjacent to arr[i]
i = i+1;
for (int k = r-1; k > q; k--, i++)
swap(a[i], a[k]);
}
// 3-way partition based quick sort
void quicksort(int a[], int l, int r)
{
if (r <= l) return;
int i, j;
// Note that i and j are passed as reference
partition(a, l, r, i, j);
// Recur
quicksort(a, l, j);
quicksort(a, i, r);
}
选择排序每次都选择一个最值,放入以排序空间内,经过n次,就排序结束每次选择最值的时候,时间复杂度 O(n)O(n)O(n),所以选择排序的时间复杂度 是O(n2)O(n^2)O(n2)优点是: 交换次数最少,是稳定排序最好/最坏时间复杂度都是O(n2)O(n^2)O(n2)void select_sort(vector<int>& nums){ for(int i = 0; i < nums.size() - 1; ++i){ int min_index = i