-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortksortedarray.py
More file actions
52 lines (51 loc) · 1.13 KB
/
sortksortedarray.py
File metadata and controls
52 lines (51 loc) · 1.13 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
47
48
49
50
51
52
class MinHeap():
def __init__(self,nums):
self.nums=self.heapify(nums)
def heapify(self,nums):
lastnonleaf=(len(nums)-2)//2
for i in reversed(range(lastnonleaf+1)):
self.siftdown(i,len(nums)-1,nums)
return nums
def siftdown(self,i,endidx,heap):
l=2*i+1
while(l<=endidx):
r=2*i+2 if 2*i+2<=endidx else -1
if r!=-1 and heap[r]<heap[l]:
smallest=r
else:
smallest=l
if heap[smallest]<heap[i]:
heap[smallest],heap[i]=heap[i],heap[smallest]
i=smallest
l=2*i+1
else:
return
def siftup(self,i,heap):
p=(i-1)//2
while(p>=0):
if heap[i]<heap[p]:
heap[p],heap[i]=heap[i],heap[p]
i=p
p=(i-1)//2
else:
return
def insert(self,val):
self.nums.append(val)
self.siftup(len(self.nums)-1,self.nums)
def ret(self):
self.nums[0],self.nums[-1]=self.nums[-1],self.nums[0]
val=self.nums.pop()
self.siftdown(0,len(self.nums)-1,self.nums)
return val
def sortKSortedArray(array, k):
H=MinHeap(array[:min(k+1,len(array))])
i=k+1
res=[]
print(H.nums)
while(i<len(array)):
res.append(H.ret())
H.insert(array[i])
i+=1
while(len(H.nums)>0):
res.append(H.ret())
return res