Divide and Conquer:
1. Divide: Partition array into 2 subarrays around pivot, such that elements in lower subarray little than pivot, and upper subarray bigger than pivot.
2. Conquer: Recursively sort the two subarrays.
3. Combine: Trivial.
Randomized QuickSort:
Idea: 1. Pivot is an random element in the array.
2. Random the Sequence of the arry.
Realize the idea1 --- CPP:
int PartitionArr(int* Arr,int p,int q){
srand((unsigned)time(NULL));
int size=q-p+1;
int index=rand()%(size)+p;
int pivot=Arr[index];
Arr[index]=Arr[p];
Arr[p]=pivot;
int i=p;
for(int j=p+1;j<p+size;j++){
if(Arr[j]<=pivot){
i++;
int tmp=Arr[i];
Arr[i]=Arr[j];
Arr[j]=tmp;
}
}
int tmp=Arr[i];
Arr[i]=Arr[p];
Arr[p]=tmp;
return i;
}
void QuickSort(int* Arr,int p,int q){
if(p<q){
int r=PartitionArr(Arr,p,q);
QuickSort(Arr,p,r-1);
QuickSort(Arr,r+1,q);
}
}
The importance of the randomized algorithm is not about the realization but understand the average Time Cost is O(nlgn). It reference to the knowledge about Probability.