Permalink
Browse files

added in-place quick sort (the proper one)

  • Loading branch information...
paulbarbu committed Mar 14, 2014
1 parent b161b5e commit 70d7780e54bdda5518251bbd747f1b6bf83a3225
Showing with 64 additions and 1 deletion.
  1. +64 −1 sort/quickSort.cpp
View
@@ -2,6 +2,38 @@
#include <vector>
#include <iostream>
+template <typename T>
+void qs(std::vector<T> &v, typename std::vector<T>::iterator start, typename std::vector<T>::iterator end){
+ if(1 >= std::distance(start,end)){
+ return;
+ }
+
+ auto mid = start;
+ std::advance(mid, std::distance(start, end)/2);
+
+ T pivot = *mid;
+ auto left=start, right=end;
+
+ while(1 <= std::distance(left, right)){
+ while(1 < std::distance(left, right) && *left < pivot){
+ left++;
+ }
+
+ while(1 <= std::distance(left, right) && *(right-1) > pivot){
+ right--;
+ }
+
+ if(1 <= std::distance(left, right)){
+ std::swap(*left, *(right-1));
+ left++;
+ right--;
+ }
+ }
+
+ qs(v, start, right);
+ qs(v, right, end);
+}
+
template <typename T>
std::vector<T> qs(std::vector<T> v){
std::vector<T> smaller, greater;
@@ -32,13 +64,44 @@ std::vector<T> qs(std::vector<T> v){
return smaller;
}
+template <typename T>
+void qs(std::vector<T> &v, int start, int end){
+ if(start >= end){
+ return;
+ }
+
+ auto mid = (start+end)/2;
+ T pivot = v[mid];
+ int left=start, right=end;
+
+ while(left < right){
+ while(left < right && v[left] < pivot){
+ left++;
+ }
+
+ while(right >= left && v[right] > pivot){
+ right--;
+ }
+
+ if(left<right){
+ std::swap(v[left], v[right]);
+ left++;
+ right--;
+ }
+ }
+
+ qs(v, start, right);
+ qs(v, right+1, end);
+}
+
int main(){
std::vector<int> foo;
foo.push_back(2);
foo.push_back(4);
foo.push_back(1);
foo.push_back(7);
- foo = qs(foo);
+
+ qs(foo, foo.begin(), foo.end());
for(auto val : foo){
std::cout<<val<<" ";

0 comments on commit 70d7780

Please sign in to comment.