-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSort.py
executable file
·80 lines (57 loc) · 2.07 KB
/
QuickSort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import random
import unittest
def quicksort(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
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)
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)
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 xrange(0, 20) ]
print("Initial array is:", array)
quicksort(array)
print("Quicksorted array is:", array)
unittest.main()