-
Notifications
You must be signed in to change notification settings - Fork 94
/
Find the Median.py
63 lines (53 loc) · 1.56 KB
/
Find the Median.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
"""
Problem Statement
In the Quicksort challenges, you sorted an entire array. Sometimes, you just need specific information about a list of
numbers, and doing a full sort would be unnecessary. Can you figure out a way to use your partition code to find the
median in an array?
"""
__author__ = 'Danyang'
class Solution(object):
def solve(self, cipher):
"""
partial quick sort
:param cipher: the cipher
"""
N, A = cipher
if N % 2 == 1:
return self.find_kth(A, 0, N - 1, (N - 1) / 2)
else:
raise IndexError
def find_kth(self, A, i, j, k):
"""
partial quick sort
"""
p = self.partition(A, i, j)
if p == k:
return A[p]
if p > k:
return self.find_kth(A, i, p - 1, k)
else:
return self.find_kth(A, p + 1, j, k)
def partition(self, A, i, j):
if i > j:
raise IndexError
if i == j:
return i
p = i
ptr_smaller = p
for ptr in xrange(p + 1, j + 1): # 1 for loop
if A[ptr] < A[p]:
ptr_smaller += 1
A[ptr], A[ptr_smaller] = A[ptr_smaller], A[ptr]
A[p], A[ptr_smaller] = A[ptr_smaller], A[p]
return ptr_smaller
if __name__ == "__main__":
import sys
f = open("1.in", "r")
# f = sys.stdin
solution = Solution()
N = int(f.readline().strip())
A = map(int, f.readline().strip().split(' '))
cipher = N, A
# solve
s = "%s\n" % (solution.solve(cipher))
print s,