Coders Packet

To implement merge sort in JAVA

By Sukriti Sinha

In this blog, we will discuss the idea of implementing merge sort in JAVA with the help of algorithm and code.

Input: We are given an array or sequence of n numbers (a1, a2 … an).

Output: A permutation (reordering) of the given sequence such that they are arranged in ascending order.

The basic idea behind insertion sort is that we use the divide and conquer approach. We divide the array into smaller subarrays, sort them and finally merge them.

Algorithm:

The Divide Step:

MergeSort(A, p, r)

                                If p > r

                                                Return

                                q = (p + r)/2

                                MergeSort(A, p, q)

                                MergeSort(A, q+1, r)

 

The merge step:

Merge(A, p, q, r)

n1 = q – p +1

n2 = r – q

let L[1 … n1 +1] and R[1 … n2 + 1] be new arrays

for i = 1 to n1

                L[i] = A[p + i – 1]

for j = 1 to n2

                R[j] = A[q +j]

L[n1 + 1] = ∞

R[n2 + 1] = ∞

i = 1

j = 1

for k = p to r

                if L[i] <= R[j]

                                A[k] = L[i]

                                i = i + 1

                else A[k] = R[j]

                                j = j +1

Download Complete Code

Comments

No comments yet