Merge Recursive Sort Implementation In Java
Sorting Techniques
import java.io.*;
class MergeSort {
private static void merge(int data[], int temp[], int low, int middle,int high)
{
int i=low;
int j= middle;
int k=low;
while(i<middle && j<=high)
{
if(temp[i] < data[j])
{
data[k] = temp[i];
k++;
i++;
}
else
{
data[k]=data[j];
k++;
j++;
}
}
while(i<middle)
{
data[k]=temp[i];
k++;
i++;
}
}
private static void mergeSortRecursive(int data[], int temp[],
int low, int high)
{
int n=high-low+1;
int middle = low + n/2;
int i;
if(n<2)
return;
for(i=low;i<middle;i++)
temp[i] = data[i];
mergeSortRecursive(temp,data, low,middle-1);
mergeSortRecursive(data,temp,middle,high);
merge(data,temp,low,middle,high);
}
public static void mergeSortP(int data[], int n)
{
mergeSortRecursive(data, new int[n], 0, n-1);
}
}
class MergeSortImpl
{
public static void main(String args[])
{
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter the array to be sorted");
int data[]=new int[10];
try
{
for(int i=0;i<10;i++)
data[i]=Integer.parseInt(in.readLine());
}
catch(Exception e) {}
MergeSort.mergeSortP(data, 10);
System.out.println("Sorted array:");
for(int i=0;i<10;i++)
System.out.println(+data[i]);
}
}
------------------------------Output---------------------------------------------
-----------------------------------------------------------------------------------
Enter the array to be sorted
4
7
1
90
3
67
23
12
67
2
Sorted array:
1
2
3
4
7
12
23
67
67
90
You Might Also Like :