The merging sort is to sort by the partition method:
(1) dividing an array into small 2 arrays and sorting them separately;
(2) Merging the sorted array after the sequence is taken;
Copy Code code as follows:
Import Java.util.Scanner;
public class MergeSort {
Int[] A=null;
Int[] B=null;
int n;
Scanner Sin=null;
MergeSort ()
{
A=new int[10000];
B=new int[10000];
Sin=new Scanner (system.in);
}
void sort (int start,int end)//Sort A[start...end]
{
int mid;
if (start >= end)//when only one element is returned directly
return;
Else
{
Mid= (End-start)/2; Divide the elements into two halves, sorted separately
Sort (start,start+mid);
Sort (start+mid+1,end);
Merge two ordered arrays A[start...start+mid] and A[start+mid+1...end]
Merge (Start,start+mid,end);
}
}
void merge (int start,int mid,int end)//merge
{
int T=start;
int i=start,j=mid+1;
while (I<=mid && j<=end)
{
if (A[i]<a[j])
B[t++]=a[i++];
Else
B[t++]=a[j++];
}
while (I<=mid)
B[t++]=a[i++];
while (J<=end)
B[t++]=a[j++];
for (i=start;i<=end;i++)//sorted content write back to the corresponding position of a array
A[i]=b[i];
}
void Run ()
{
System.out.print ("Enter the number of numbers to be sorted:");
N=sin.nextint ();
for (int i=0;i<n;i++)
A[i]=sin.nextint ();
Sort (0,n-1);
System.out.println ("The sort result is:");
Enter the data to sort
for (int i=0;i<n;i++)
System.out.println (a[i]+ "");
}
public static void Main (string[] args) {
New MergeSort (). run ();
}
}