Java Merge Sort

Sharing is healthy !!

Today in this post you will learn java merge sort. Basically merge sort java program is used to sort group of objects.

what is merge sort?

Merge sort is basically an algorithm. Widely known as divide and conquer algorithm.

In merge sort original elements are divided into smaller elements of data to sort the given integer elements.

Java Merge Sort

example: Java Merge Sort

Also Read¬†–¬†Bubble Sort Java Program

import java.util.Scanner;

// Class Java_Merge_Sort
public class Java_Merge_Sort {

// Java merge sort function

public static void sorting(int x[], int low, int high)
{
int M = high - low;

if(M <= 1)
return;

int middle = low + M / 2;

// recursive sort
sorting(x, low, middle);
sorting(x, middle, high);

// now merge two sorted subarrays
int temp[] = new int[M];
int m = low;
int n = middle;

for(int y = 0;y < M;y++)
{
if(m == middle)
temp[y] = x[n++];
else if(n == high)
temp[y] = x[m++];
else if(x[n] < x[m])
temp[y] = x[n++];
else
temp[y] = x[m++];
}

for(int y = 0;y < M;y++)
x[low + y] = temp[y];
}

// Main method starts here
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Java Merge Sort\n");
int n;
int i;

// User entering number of elements
System.out.println("Please enter number of integers: ");
n = sc.nextInt();

// Creating array of n integers
int array[] = new int[n];

// Receiving integers
System.out.println("\nPlease enter " + n + " integer elements: ");
for(i = 0;i < n;i++)
array[i] = sc.nextInt();

// Call sorting method
sorting(array, 0, n);

// Printing sorted array
System.out.println("Integers after sorting: ");
for(i = 0;i < n;i++)
System.out.print(array[i] + " ");
System.out.println();
}
}

Output:

Java Merge Sort

Please enter number of integers: 6

Please enter 6 integer elements: 33 00 55 11 22 44
Integers after sorting: 0 11 22 33 44 55

Sharing is healthy !!

Leave a Reply

Your email address will not be published.