IMPORTANT
THIS IS NOTE I MADE WHEN STUDY C++ ALGORITHM
THIS NOTE WOULD ONLY HELP U SPEND LESS TIME ON UNDERSTNDING THE ALGORITHM AND CODE IMPLEMENTATION
ALL WORDS IN " " ARE DIRECTLY REFERENCE
ALL CODE IMPLEMATATION ARE DIRECTLY REFERENCE
PLEASE CLICK THE LINK BELOW TO READ ORIGINAL BOOK AND INSTRUCTION
https://cathyatseneca.gitbook.io/data-strutures-and-algorithms/
Quick Sort
Part A:
template <class TYPE>
void QuickSort(vector<TYPE>& arr){
QuickSort(arr,0,arr.size()-1);
}
Part B:
template <class TYPE>
void QuickSort(vector<TYPE>& arr, int left, int right){
if(right-left <=3){
InsertionSort(arr,left,right);
}
else{
int pivotpt=right;
int i=left;
int j=right-1;
TYPE pivot=arr[pivotpt];
while(i<j){
while(arr[i]<pivot) i++;
while(arr[j]>pivot) j--;
if(i<j)
swap(arr[i++],arr[j--]);
}
swap(arr[i],arr[pivotpt]);
QuickSort(arr,left,i-1);
QuickSort(arr,i+1,right);
}
}
- sort with “jumping”
- run time depends on different situation:
- the best situation: O(nlogn)
- the worst situation is: O(n^2)
- (index might change if there are some data with same value)?
- Recursice concept is needed
TO implement this, a pivot point is needed.
PArt A create a new prototype for the function in partB.
In part B,
A pivot point is decleared with the most right value in the array.
In the first while-loop ensures i and j will meet each other,
and this is exact location of pivot point;
the following two while-loop finds the number smaller than pivot and larger than pivot respectively;
when those two numbers are finded,
switch their positions and continue.
Placed the pivot point in correct location represent the end of the firsr round,
repeat above step recursively by dividing this array into two pieces,
pivot uses to indetify the break.