Skip to content

Instantly share code, notes, and snippets.

@paulbarbu
Last active December 16, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulbarbu/5445031 to your computer and use it in GitHub Desktop.
Save paulbarbu/5445031 to your computer and use it in GitHub Desktop.
Quicksort
#include <vector>
#include <iostream>
template <typename T>
std::vector<T> qs(std::vector<T> v){
std::vector<T> smaller, greater;
T pivot;
if(!v.size()){
return smaller;
}
pivot = v.back();
v.pop_back();
for(T val : v){
if(val <= pivot){
smaller.push_back(val);
}
else{
greater.push_back(val);
}
}
smaller = qs(smaller);
greater = qs(greater);
smaller.push_back(pivot);
smaller.insert(smaller.end(), greater.begin(), greater.end());
return smaller;
}
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);
for(auto val : foo){
std::cout<<val<<" ";
}
std::cout<<"\n";
}
qs :: (Ord a) => [a] -> [a]
qs [] = []
qs (x:xs) = qs [y | y <- xs, y <= x] ++ [x] ++ qs [y | y <- xs, y > x]
def qs(v):
if len(v) == 0:
return list()
pivot = v[len(v)//2]
v.remove(pivot)
smaller = qs([x for x in v if x <= pivot])
greater = qs([x for x in v if x > pivot])
smaller.append(pivot)
smaller.extend(greater)
return smaller
if __name__ == '__main__':
print(qs([1, 3, 5, 3, 2, 7]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment