Last active
December 16, 2015 13:58
-
-
Save paulbarbu/5445031 to your computer and use it in GitHub Desktop.
Quicksort
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> | |
#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"; | |
} |
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
qs :: (Ord a) => [a] -> [a] | |
qs [] = [] | |
qs (x:xs) = qs [y | y <- xs, y <= x] ++ [x] ++ qs [y | y <- xs, y > x] |
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
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