Merge sort program in java with output

Merge sort program in java with output. This program will execute the output using merge sort concept with array in java programming language. In Java programs, this program will organise data in a specific order. For beginners,it will print the initialised value as a single result in java. Merge sort is a comparison-based, efficient, and general-purpose sorting algorithm. The majority of implementations generate a consistent type, which means that equivalent elements are sorted in the same order i/o.

import java.util.Arrays;
class Main 
{
void merge(int array[], int p, int q, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int L[] = new int[n1];
int M[] = new int[n2];
for (int i = 0; i < n1; i++)
L[i] = array[p + i];
for (int j = 0; j < n2; j++)
M[j] = array[q + 1 + j];
int i, j, k;
i = 0;
j = 0;
k = p;
while (i < n1 && j < n2) 
{
if (L[i] <= M[j]) {
array[k] = L[i];
i++;
} else
{
array[k] = M[j];
j++;
}
k++;
}
while (i < n1) 
{
array[k] = L[i];
i++;
k++;
}
while (j < n2) {
array[k] = M[j];
j++;
k++;
}
}
void sort(int array[], int lhs, int rhs) {
if (lhs < rhs)
{
int mid = (lhs + rhs) / 2;
sort(array, lhs, mid);
sort(array, mid + 1, rhs);
merge(array, lhs, mid, rhs);
}
}
public static void main(String args[]) 
{
int[] array = {56,666,33,4644,6865,234 };
Main ob = new Main();
ob.sort(array, 0, array.length - 1);
System.out.println("after sorting");
System.out.println(Arrays.toString(array));
}
}

 

Output:

after sorting 

[33, 56, 234, 666, 4644, 6865]