Merge Sort using
‘Java’
Consolidate sort is a well known arranging calculation that follows the separation and-vanquish approach. It isolates the unsorted rundown into more modest sublists, recursively sorts them, and afterward combines them back to create an arranged rundown. Blend sort has a period intricacy of O(n log n), making it an effective arranging calculation for huge datasets.
Program:-
import java.util.Scanner;
class MergeSort
{
int sort1(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
// recursively sort
sort1(a, low, mid);
sort1(a, mid, high);
// merge two sorted subarrays
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter No. of Elements: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.print("Enter "+n+" Elements:
");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
MergeSort ms=new MergeSort();
ms.sort1(a,0,n);
System.out.print("Array After Merge Sort is:
");
for(int i=0;i<n;i++)
System.out.print(" "+a[i]);
}
}
Output:
0 Comments