Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a code for merging K sorted arrays #4932

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions code/unclassified/src/Merge_K_sorted/Merge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@

import sys
from typing import List, Optional
Matrix = List[List[int]]


class MinHeapNode:
def __init__(self, el, i, j):
self.element = el
self.i = i
self.j = j

class MinHeap:
def __init__(self, ar: List[MinHeapNode], size: int):
"""

:type ar: object
"""
self.heap_size = size
self.heap_arr = ar
i = (self.heap_size - 1) // 2
while i >= 0:
self.__min_heapify__(i)
i -= 1


def __min_heapify__(self, i):
l = __left__(i)
r = __right__(i)
smallest = i
if l < self.heap_size and self.heap_arr[l].element < self.heap_arr[i].element:
smallest = l
if r < self.heap_size and self.heap_arr[r].element < self.heap_arr[smallest].element:
smallest = r
if smallest != i:
__swap__(self.heap_arr, i, smallest)
self.__min_heapify__(smallest)

def __get_min__(self) -> Optional:
if self.heap_size <= 0:
print('Heap underflow')
return None
return self.heap_arr[0]


def __replace_min__(self, root):
self.heap_arr[0] = root
self.__min_heapify__(0)


def __left__(i):
return 2 * i + 1


def __right__(i):
return 2 * i + 2


def __swap__(arr: List[MinHeapNode], i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp


def __merge_k_sorted_arrays__(arr: Matrix, k: int):
# type: (object, object) -> object
h_arr = []
result_size = 0
for i in range(len(arr)):
node = MinHeapNode(arr[i][0], i, 1)
h_arr.append(node)
result_size += len(arr[i])

min_heap = MinHeap(h_arr, k)
result = [0]*result_size
for i in range(result_size):
root = min_heap.__get_min__()
result[i] = root.element
if root.j < len(arr[root.i]):
root.element = arr[root.i][root.j]
root.j += 1
else:
root.element = sys.maxsize
min_heap.__replace_min__(root)
for x in result:
print(x, end=' ')
print()


if __name__ == '__main__':
arr = [
[1, 2, 12, 20],
[1, 10, 15, 1003],
[23, 30, 45, 1500]
]
print('Merged Array is:')
__merge_k_sorted_arrays__(arr, len(arr))