forked from OliverIgnetik/Data-Structures-Algorithms-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.py
More file actions
86 lines (60 loc) · 2.2 KB
/
Copy pathquickSort.py
File metadata and controls
86 lines (60 loc) · 2.2 KB
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
81
82
83
84
85
86
# SOLUTION 1
def quicksort(array, left, right):
if left < right:
pivot = right
partitionindex = partition(array, pivot, left, right)
quicksort(array, left, partitionindex - 1)
quicksort(array, partitionindex + 1, right)
return array
def partition(array, pivot, left, right):
pivotvalue = array[pivot]
partitionindex = left # keeps track of the last swap
for i in range(left, right):
if array[i] < pivotvalue:
swap(array, i, partitionindex)
partitionindex += 1
# final swap to complete partition
swap(array, right, partitionindex)
return partitionindex
def swap(array, firstindex, secondindex):
array[firstindex], array[secondindex] = array[secondindex], array[firstindex]
# SOLUTION 2
def quick_sort_alt(arr):
return quick_sort_help(arr, 0, len(arr)-1)
def quick_sort_help(arr, first, last):
if first < last:
# find the split point
splitpoint = partition_alt(arr, first, last)
# split the list
quick_sort_help(arr, first, splitpoint-1)
quick_sort_help(arr, splitpoint+1, last)
return arr
def partition_alt(arr, first, last):
pivotvalue = arr[first]
leftmark = first+1
rightmark = last
done = False
while not done:
# increment leftmark
while leftmark <= rightmark and arr[leftmark] <= pivotvalue:
leftmark += 1
# increment rightmark
while arr[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark -= 1
# stop once we find the split point
if rightmark < leftmark:
done = True
# swap left and right mark
else:
swap_alt(arr, leftmark, rightmark)
# do the final swap
swap_alt(arr, first, rightmark)
return rightmark
def swap_alt(array, firstindex, secondindex):
array[firstindex], array[secondindex] = array[secondindex], array[firstindex]
numbers = [8, 9, 4, 3, 5, 1]
# Select first and last index as 2nd and 3rd parameters
# print(quick_sort_alt(numbers))
partition_test = [1, 3, 10, 8, 5, 4, 7, 6]
partition(partition_test, len(partition_test) - 1, 0, len(partition_test)-1)
print(quicksort(numbers, 0, len(numbers)-1))