Skip to content

Instantly share code, notes, and snippets.

@uolter
Created December 29, 2014 10:27
Show Gist options
  • Save uolter/a04109b822c2b1ad9281 to your computer and use it in GitHub Desktop.
Save uolter/a04109b822c2b1ad9281 to your computer and use it in GitHub Desktop.
Simple Quck Sort example with python
#!/usr/bin/env
# -*- coding: utf-8 -*-
import unittest
""" Quicksort implementation """
def quicksort(arr):
""" Quicksort a list
:type arr: list
:param arr: List to sort
:returns: list -- Sorted list
"""
if not arr:
return []
pivots = [x for x in arr if x == arr[0]]
lesser = quicksort([x for x in arr if x < arr[0]])
greater = quicksort([x for x in arr if x > arr[0]])
return lesser + pivots + greater
class TestQuickSort(unittest.TestCase):
def setUp(self):
pass
def test_emptylist(self):
self.assertEqual(quicksort([]), [])
def test_onesizelist(self):
self.assertEqual(quicksort([1]), [1])
def test_sortedlist(self):
self.assertEqual(quicksort([1, 2, 3]), [1, 2, 3])
def test_unsortedlist(self):
self.assertEqual(quicksort([1, 3, 2]), [1, 2, 3])
def test_equallist(self):
self.assertEqual(quicksort([3, 3, 3, 3, 3]), [3, 3, 3, 3, 3])
def test_chars(self):
self.assertEqual(quicksort(list('street')), ['e', 'e', 'r', 's', 't', 't'])
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment