forked from mejtfk/Algorithms-HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.py
More file actions
36 lines (30 loc) · 706 Bytes
/
quicksort.py
File metadata and controls
36 lines (30 loc) · 706 Bytes
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
'''
Algorithm used from pseudo-code from Introduction to Algorthms Third Edition, MIT Press
'''
def swap(A,i,j):
x=A[i]
A[i]=A[j]
A[j]=x
return A
def partition(A, p, r):
x=A[r]
i=p-1
for j in (range(p,r)):
if A[j] <= x:
i+=1
swap(A,i,j)#exchange A[i] with A[j]
swap(A,i+1,r)#exchange A[i+1] with A[r]
return i+1
def quicksort(A, p, r):
if p < r:
q = partition(A, p, r)
quicksort(A, p, q-1)
quicksort(A, q+1, r)
if __name__ == '__main__':
A=[2,8,7,1,3,5,6,4]
print("Before sorting: ", end='')
print(A)
print()
print("After sorting: ", end='')
quicksort(A, 0, len(A)-1)
print(A)