Merge Sort Program in Java With Output

Merge sort in java program. 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.

Merge Sort in Java Program

A data-sequencing technique that involves continuously merging items in a list. Each item in the initial unordered list is merged with another, resulting in two-item groupings. Every two-item group is merged, resulting in four-item groups, and so on, until only one ordered list remains.

Merge sort is a general-purpose, comparison-based sorting algorithm used in computer science. The majority of implementations result in a stable sort, which indicates that the order of equal elements in the input and output is the same.

Array in Java

In Java, an array is a collection of variables that are referred to by a single variable name and an index number. An array’s items are called elements. An array’s items must all be of the same type. A data structure that contains a group of elements is known as an array. These items are often all of the same data type, such as an integer or a string.

Sort in Java Program

To sort data in an array, use the sort function. It’s advisable to use the sortby function to sort data in the grid because it’s more versatile. Because it refers to a range, sortby will respect column additions/deletions, whereas sort refers to a column index number.

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]