Java two-way merge sort sample sharing _java

Source: Internet
Author: User

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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.