From 9640f596c6f5b146ae14b6198e15f74c421b77c0 Mon Sep 17 00:00:00 2001 From: "U-GT780R-W7HP\\stephen" Date: Fri, 7 Oct 2011 17:18:46 -0400 Subject: [PATCH] In-place quicksort in Python --- QuickSort.py | 85 ++++++++++++++++++++++++++++++++++++++++++---------- README | 2 +- 2 files changed, 70 insertions(+), 17 deletions(-) diff --git a/QuickSort.py b/QuickSort.py index e86f812..37a8556 100755 --- a/QuickSort.py +++ b/QuickSort.py @@ -1,27 +1,80 @@ import random +import unittest def quicksort(array): - if len(array) < 2: - return array + def swap(a, b): + temp = array[a] + array[a] = array[b] + array[b] = temp + + def partition(array, begin, end): + # pick pivot elem and move to end + pivotIndex = random.randint(begin, end) + pivotElem = array[pivotIndex] + swap(pivotIndex, end) + + swapindex = begin + for i in xrange(begin, end): + if array[i] < pivotElem: + swap(swapindex, i) + swapindex += 1 + + swap(swapindex, end) + return swapindex - # select a random pivot - pivot = array[random.randint(0, len(array) - 1)] - array.remove(pivot) - - less = [] - greater = [] + def doquicksort(array, begin, end): + arraylen = end-begin+1 + + if arraylen < 2: + return + + pivotIndex = partition(array, begin, end) + + doquicksort(array, begin, pivotIndex-1) + doquicksort(array, pivotIndex+1, end) + + doquicksort(array, 0, len(array)-1) - for elem in array: - if elem < pivot: - less.append(elem) - else: - greater.append(elem) +class QuickSortTestFunctions(unittest.TestCase): + + def isSorted(self, array): + if len(array) < 2: + return True + + prev_index = 0 + + for i in xrange(1, len(array)): + if array[prev_index] > array[i]: + return False + prev_index = i + + return True + + def sort_and_test(self, array): + quicksort(array) + return self.isSorted(array) - return quicksort(less) + [pivot] + quicksort(greater) + def test_sorted_empty(self): + self.assertTrue(self.sort_and_test([])) + + def test_sorted_one(self): + self.assertTrue(self.sort_and_test([1])) + + def test_sorted_two(self): + self.assertTrue(self.sort_and_test([2,1])) + self.assertTrue(self.sort_and_test([1,1])) + + def test_random(self): + for i in xrange(0, 100): + array = [ random.randint(-1000000, 1000000) for j in xrange(0, random.randint(20,100))] + self.assertTrue(self.sort_and_test(array)) if __name__ == "__main__": - array = [ random.randint(0, 100) for i in range(0, 10) ] + array = [ random.randint(0, 100) for i in xrange(0, 20) ] print("Initial array is:", array) - print("Quicksorted array is:", quicksort(array)) + quicksort(array) + print("Quicksorted array is:", array) + + unittest.main() \ No newline at end of file diff --git a/README b/README index c197a0d..68ba153 100644 --- a/README +++ b/README @@ -1,4 +1,4 @@ Quicksort in Python -Naive implementation using O(n) memory +In-place implementation