Created
May 27, 2012 06:45
-
-
Save diogobaeder/2802479 to your computer and use it in GitHub Desktop.
Quicksort memorization
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
#!/usr/bin/env python | |
''' | |
Just another quicksort implementation, to see if I memorized the algorithmn. | |
Apparently, yes. :-) | |
Gotchas during the implementation: | |
- forgot to check min and max in the beginning, got IndexError | |
- choosing nonsense as pivot led me to almost-sorted list (worked when | |
I stopped being stupid) | |
''' | |
def sort(l): | |
partition(l, 0, len(l) - 1) | |
def partition(l, min, max): | |
if max <= min: | |
return | |
pivot = (max + min) // 2 # better if random, but I want to go bare | |
pivot_value = l[pivot] | |
l[pivot], l[max] = l[max], l[pivot] | |
store = min | |
for i in range(min, max): | |
if l[i] <= pivot_value: | |
l[i], l[store] = l[store], l[i] | |
store += 1 | |
l[store], l[max] = l[max], l[store] | |
partition(l, min, store -1) | |
partition(l, store + 1, max) | |
if __name__ == '__main__': | |
import random | |
l = range(100000) | |
random.shuffle(l) | |
sort(l) | |
assert l == sorted(l) | |
print 'sorted!' |
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
import random | |
from unittest import TestCase | |
from nose.tools import istest | |
import sorter | |
class SorterTest(TestCase): | |
@istest | |
def sorts_simple_list(self): | |
"""Sorts a simple list""" | |
some_list = [3, 1, 2] | |
sorter.sort(some_list) | |
self.assertEqual(some_list, [1, 2, 3]) | |
@istest | |
def sorts_a_bigger_list(self): | |
"""Sorts a somewhat bigger list""" | |
some_list = [5, 7, 3, 8, 9] | |
sorter.sort(some_list) | |
self.assertEqual(some_list, [3, 5, 7, 8, 9]) | |
@istest | |
def sorts_a_huge_list(self): | |
"""Sorts a huge list""" | |
num_elements = 100 | |
some_list = range(num_elements) | |
random.shuffle(some_list) | |
sorter.sort(some_list) | |
self.assertEqual(some_list, list(range(num_elements))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment