forked from utkarsh-shekhar/basic-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.py
More file actions
46 lines (30 loc) · 1.01 KB
/
Copy pathquicksort.py
File metadata and controls
46 lines (30 loc) · 1.01 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
from random import randint
def _quicksort(arr, lo, hi):
if lo < hi:
p = partition(arr, lo, hi)
_quicksort(arr, lo, p-1)
_quicksort(arr, p+1, hi)
def partition(arr, lo, hi):
#pivot is chosen as first element of list
#shuffle pivot ie first element with any other element randomly
randidx = randint(lo,hi)
arr[randidx], arr[lo] = arr[lo], arr[randidx]
pivot = arr[lo]
left, right = lo, hi
while True:
while arr[left] <= pivot:
left += 1
if left == hi:
break
while arr[right] > pivot:
right -= 1
if right == lo:
break
if (left >= right):
break
arr[left], arr[right] = arr[right], arr[left]
arr[lo], arr[right] = arr[right], arr[lo]
return right
def quicksort(arr):
if type(arr) is list:
_quicksort(arr, 0, len(arr)-1)