Skip to content

Commit 9cf5aef

Browse files
dionmisicOmkarPathak
authored andcommitted
Added Quickselect algorithm
* Added Quickselect algorithm
1 parent 76b2750 commit 9cf5aef

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

pygorithm/searching/quickselect.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Author: DION MISIC
2+
# Created On: 11th August 2017
3+
4+
def quickselect(array, n):
5+
''' Recursively defined function for finding nth number in unsorted list '''
6+
def select(array, left, right, n):
7+
if left == right:
8+
return array[left]
9+
split = partition(array, left, right, n)
10+
length = split - left + 1
11+
if length == n:
12+
return array[split]
13+
elif n < length:
14+
return select(array, left, split - 1, n)
15+
else:
16+
return select(array, split + 1, right, n - length)
17+
18+
def partition(array, left, right, pivot):
19+
pivot_val = array[pivot]
20+
array[pivot], array[right] = array[right], array[pivot]
21+
store_index = left
22+
23+
for i in range(left, right):
24+
if array[i] < pivot_val:
25+
array[store_index], array[i] = array[i], array[store_index]
26+
store_index += 1
27+
28+
array[right], array[store_index] = array[store_index], array[right]
29+
return store_index
30+
31+
ans = select(array, 0, len(array) - 1, n)
32+
return ans
33+
34+
def time_complexities():
35+
''' Time Complexity '''
36+
return '''Best Case: O(n), Average Case: O(n), Worst Case: O(n^2)'''
37+
38+
def get_code():
39+
''' Standard code inspection '''
40+
import inspect
41+
return inspect.getsource(quickselect)

0 commit comments

Comments
 (0)