Last active
March 22, 2020 20:47
-
-
Save TalissonBento/f6477bed26ec197918292805ecd3fbdf to your computer and use it in GitHub Desktop.
Recursive Quicksort C++ Implementation
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
//============================================================================ | |
// Name : QuickSort.cpp | |
// Author : Talisson Bento | |
// Version : | |
// Copyright : Your copyright notice | |
// Description : Sort in C++, Ansi-style | |
//============================================================================ | |
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <chrono> | |
using namespace std; | |
class Timer | |
{ | |
public: | |
Timer() | |
{ | |
this->reset(); | |
} | |
void reset() | |
{ | |
this->start_ = std::chrono::high_resolution_clock::now(); | |
} | |
long elapsed() | |
{ | |
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - this->start_).count(); | |
} | |
private: | |
std::chrono::steady_clock::time_point start_; | |
}; | |
template<class Iterator> | |
Iterator partition(Iterator start, Iterator end) | |
{ | |
Iterator middle = start + static_cast<int>(std::distance(start, end) / 2); | |
std::iter_swap(start, middle); | |
Iterator pivot = start; | |
Iterator left = std::next(start); | |
while(start != end) | |
{ | |
if(*start < *pivot) | |
{ | |
std::iter_swap(left, start); | |
++left; | |
} | |
++start; | |
} | |
std::advance(left, -1); | |
std::iter_swap(left, pivot); | |
return left; | |
} | |
template<class Iterator> | |
void recursive_quicksort(Iterator start, Iterator end) | |
{ | |
if(std::distance(start, end) > 1) | |
{ | |
Iterator pivot = partition(start, end); | |
recursive_quicksort(start, pivot); | |
recursive_quicksort(pivot, end); | |
} | |
} | |
int main() | |
{ | |
Timer timer; | |
std::srand(0); | |
vector<int> container(1000000); | |
std::generate(container.begin(), container.end(), std::rand); | |
timer.reset(); | |
recursive_quicksort(container.begin(), container.end()); | |
std::cout << "sort "<< container.size() << " items in " << timer.elapsed() << " ms" << std::endl; | |
/*int i =1; | |
for(auto& it : container) | |
{ | |
//cout << "#" << i++ << "\t" << it << endl; | |
}*/ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment