Created
April 12, 2019 18:56
-
-
Save iwatakeshi/7f7a7c11cd7a6f76598df18a7ecda507 to your computer and use it in GitHub Desktop.
Quicksort in C++
This file contains hidden or 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
#include <vector> | |
template<class T> | |
void quick_sort(std::vector<T>& list); | |
template<class T> | |
void quick_sort(std::vector<T>& list, int start, int end); | |
template<class T> | |
int partition(std::vector<T>& list, int start, int end, int pivot); | |
template<class T> | |
void quick_sort(std::vector<T>& list) { | |
quick_sort(list, 0, list.size() - 1); | |
} | |
template<class T> | |
void quick_sort(std::vector<T>& list, int start, int end) { | |
int pivot = list[(start + end) / 2]; | |
int index = partition(list, start, end, pivot); | |
quick_sort(list, start, index - 1); | |
quick_sort(list, index, end); | |
} | |
template<class T> | |
int partition(std::vector<T>& list, int start, int end, int pivot) { | |
int left = start, right = end; | |
while(left <= right) { | |
while (list[left] < pivot) left++; | |
while (list[right] > pivot) right--; | |
if (left <= right) { | |
std::swap(list[left], list[right]); | |
left++, right--; | |
} | |
} | |
return left; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment