Skip to content

Commit f2632fe

Browse files
committed
added inplace version of quick sort
1 parent 950d7d5 commit f2632fe

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
quick_sort_in_place.py
3+
4+
Implementation of quick sort on a list and returns a sorted list.
5+
In-place version.
6+
7+
Quick Sort Overview:
8+
------------------------
9+
Uses partitioning to recursively divide and sort the list
10+
11+
Time Complexity: O(n**2) worst case
12+
13+
Space Complexity: O(log n) this version
14+
15+
Stable: No
16+
17+
Psuedo Code: http://en.wikipedia.org/wiki/Quicksort#In-place_version
18+
19+
"""
20+
21+
def partition(seq, left, right, pivot_index):
22+
pivot_value = seq[pivot_index]
23+
seq[pivot_index], seq[right] = seq[right], seq[pivot_index]
24+
store_index = left
25+
for i in range( left, right ):
26+
if seq[i] < pivot_value:
27+
seq[i], seq[store_index] = seq[store_index], seq[i]
28+
store_index += 1
29+
seq[store_index], seq[right] = seq[right], seq[store_index]
30+
return store_index
31+
32+
def sort(seq, left, right):
33+
"""in-place version of quicksort"""
34+
from random import randrange
35+
if len(seq) <= 1:
36+
return seq
37+
elif left < right:
38+
#pivot = (left+right)/2
39+
pivot = randrange(left, right)
40+
pivot_new_index = partition(seq, left, right, pivot)
41+
sort(seq, left, pivot_new_index - 1)
42+
sort(seq, pivot_new_index + 1, right)
43+
return seq

algorithms/tests/test_sorting.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import random
22
import unittest
33
from ..sorting import bubble_sort, selection_sort, insertion_sort, \
4-
merge_sort, quick_sort, heap_sort, shell_sort, comb_sort, cocktail_sort
4+
merge_sort, quick_sort, heap_sort, shell_sort, comb_sort, cocktail_sort, \
5+
quick_sort_in_place
56

67

78
class SortingAlgorithmTestCase(unittest.TestCase):
@@ -73,6 +74,22 @@ def test_quicksort(self):
7374
self.assertEqual(self.correct, self.output)
7475

7576

77+
class TestQuickSortInPlace(SortingAlgorithmTestCase):
78+
"""
79+
Tests Quick sort in place version on a small range from 0-9
80+
also tests partition function included in quick sort
81+
"""
82+
def test_quicksort_in_place(self):
83+
self.output = quick_sort_in_place.sort(self.input, 0,
84+
len(self.input)-1)
85+
self.assertEqual(self.correct, self.output)
86+
87+
def test_partition(self):
88+
self.seq = range(10)
89+
self.assertIs(quick_sort_in_place.partition(self.seq, 0,
90+
len(self.seq)-1, 5), 5)
91+
92+
7693
class TestHeapSort(SortingAlgorithmTestCase):
7794
"""
7895
Test Heap sort on a small range from 0-9

0 commit comments

Comments
 (0)