Last active
June 17, 2019 06:29
-
-
Save geniuszxy/0603d5d12a4c2b7ab6c514847c54d32d to your computer and use it in GitHub Desktop.
Quick Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Swap(int array[], int a, int b) | |
{ | |
int tmp = array[a]; | |
array[a] = array[b]; | |
array[b] = tmp; | |
} | |
void PrintArray(int array[], int length, int lower, int upper) | |
{ | |
for (int i = 0; i < length; ++i) | |
{ | |
if (i == lower || i == upper) | |
cout << '[' << array[i] << "] "; | |
else | |
cout << array[i] << ' '; | |
} | |
cout << endl; | |
} | |
void PrintRange(int array[], int length, int begin, int end) | |
{ | |
for (int i = 0; i < length; ++i) | |
{ | |
if (i == begin) | |
cout << '<'; | |
cout << array[i]; | |
if (i == end) | |
cout << '>'; | |
cout << ' '; | |
} | |
cout << endl; | |
} | |
//Partition the array within range [lower, upper] into 2 parts | |
int Partition(int array[], int lower, int upper) | |
{ | |
PrintRange(array, 9, lower, upper); | |
//Is lower index represent the base value | |
bool base_lower = true; | |
while (upper > lower) | |
{ | |
PrintArray(array, 9, lower, upper); | |
if (array[lower] > array[upper]) | |
{ | |
Swap(array, lower, upper); | |
//After swap | |
PrintArray(array, 9, lower, upper); | |
base_lower = !base_lower; | |
} | |
//If base value is on the lower side, check the next upper value | |
if (base_lower) | |
{ | |
upper--; | |
} | |
//If base value is on the upper side, check the next lower value | |
else | |
{ | |
lower++; | |
} | |
} | |
return lower; | |
} | |
void QuickSort(int array[], int lower, int upper) | |
{ | |
if (lower < upper) | |
{ | |
int p = Partition(array, lower, upper); | |
QuickSort(array, lower, p - 1); //Sort lower part | |
QuickSort(array, p + 1, upper); //Sort upper part | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment