-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathKth_smallest_element.py
64 lines (49 loc) · 1.25 KB
/
Kth_smallest_element.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
# Input:
# N = 6
# arr[] = 7 10 4 3 20 15
# K = 3
# Output : 7
# Explanation :
# 3rd smallest element in the given
# array is 7.
# def kthSmallest(arr, l, r, k):
# '''
# arr : given array
# l : starting index of the array i.e 0
# r : ending index of the array i.e size-1
# k : find kth smallest element and return using this function
# '''
# arr.sort()
# return(arr[k-1])
# r=int(input())
# arr=input()
# array=list(map(int,arr.strip().split()))
# k=int(input())
# print(kthSmallest(array,0,r-1,k))
def kthSmallest(arr, l, r, k):
if k > 0 and k <= r - l + 1:
pos = randomPartition(arr, l, r)
if pos - l == k - 1:
return arr[pos]
if pos - l > k - 1:
return kthSmallest(arr, l, pos - 1, k)
return kthSmallest(arr, pos + 1, r, k - pos + l - 1)
return 999999999999
def swap(arr, a, b):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def partition(arr, l, r):
x = arr[r]
i = l
for j in range(l, r):
if arr[j] <= x:
swap(arr, i, j)
i += 1
swap(arr, i, r)
return i
def randomPartition(arr, l, r):
n = r - l + 1
pivot = int(random.random() % n)
swap(arr, l + pivot, r)
return partition(arr, l, r)