You are on page 1of 3

Assignment 7

-----------------------------------------------------------------------------------
1. Implement k-way merge sort. The size of the input array is 100. Use
file to store the elements. Value of k will be given as input.
K-Way Merge Sort:
K Way merge sort is a sorting algorithm that organizes a list of
elements by dividing it into smaller parts, sorting each part and then
merging it back together.

ALGORITHM:
There are two functions in the code. They are kWayMergeSort and
mergeKArrays. The algorithms the respective functions are as follows:
The kWayMergeSort is the function which breaks the array and sorts
the distinguished elements.
The mergeKArrays function sorts and merges the divided arrays in to
the main array.
Algorithm for kWayMergeSort(arr, k):
if length(arr) <= 1:
return arr
n = length(arr)
subArraySize = n / k
extra = n % k
subArrays[k]
for i from 0 to k-1:
subArrays[i] = arr[i * subArraySize : (i + 1) * subArraySize]
if extra > 0:
subArrays[extra] = arr[extra * (subArraySize + 1) : n]
for i from 0 to k-1:
subArrays[i] = kWayMergeSort(subArrays[i], k)
result = mergeKArrays(subArrays, k)
return result

Algorithm for mergeKArrays(arrays, k):


result[ ]
indices[k] = {0}
while true:
minVal = Infinity
minIndex = -1
for i from 0 to k-1:
If indices[i] < length(arrays[i]) and arrays[i][indices[i]] < minVal:
minVal = arrays[i][indices[i]]
minIndex = i
if minIndex == -1:
break
result.append(minVal)
indices[minIndex]++
return result
ult

You might also like