CTCI 5th中提到了quicksort partition中的另一种写法,感觉比算法导论上的更容易理解,更直观。
其中需要注意的是:
1) while(A[left] < pivot) left++; 该处不能使用==符号,否则所有元素相等时,没有办法进行partition,将会出现infinate looping
2) pivot的选取,可以选取[start, end]中任何一个,或者随机选取。
3) return left-1,是partition的左半部分的最有一个元素的Index。
Quick Partition代码如下:
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int partition(int A[], int s, int e)
{
int len = e-s+1;
int pivot = A[rand()%(e-s+1)+s];
int left = s, right = e;
while(left <= right)
{
while(A[left] < pivot) left++;
while(A[right] > pivot) right--;
if(left <= right)
{
swap(A[left], A[right]);
left++;
right--;
}
}
return left-1;
}
int select_kth(int A[], int s, int e, int k)
{
int left_last = partition(A, s, e);
int left_index = left_last - s;
if(k == left_index)
return A[left_last];
else if(left_index > k)
return select_kth(A, s, left_last, k);
else
return select_kth(A, left_last+1, e, k-(left_index+1));
}
int main()
{
int n = 5000;
int a[n];
int b[n];
for(int i=0; i<n; i++)
{
a[i] = rand()%10000;
b[i] = a[i];
}
cout << endl;
sort(b, b+n);
for(int i=0; i<n; i++)
{
if(select_kth(a,0,n-1,i) != b[i])
cout << "error " << endl;
}
return 0;
}