Merge Sort Example-java

Source: Internet
Author: User

/**
* Merge two ordered tables
* @param array
* @param start position
* @param mid first series end position
* @param end position of the second sequence
* @return
*/
public static void Merge (int[] array,int start,int mid,int end)
{
Int[] result = new Int[end-start+1];
int aindex = start;
int bindex = mid+1;
int resultindex = 0;
while (Aindex<=mid&&bindex<=end)
{
if (Array[aindex]>array[bindex])
{
Result[resultindex] = Array[aindex];
aindex++;
}
Else
{
Result[resultindex] = Array[bindex];
bindex++;
}
resultindex++;
}
while (Aindex<=mid)
{
Result[resultindex] = Array[aindex];
aindex++;
resultindex++;
}
while (Bindex<=end)
{
Result[resultindex] = Array[bindex];
bindex++;
resultindex++;
}
Copyarray (Result,array,start);
}
/**
* Copy
* @param sourcearray
* @param Targetarray
* @param starting position of start Targetarray
*/
public static void Copyarray (int[] sourcearray,int[] targetarray,int start)
{
for (int i=0;i<sourcearray.length;i++)
{
Targetarray[start+i] = Sourcearray[i];
}
}
/**
*
* @param array
* @param start position
* @param End Position
*/
public static void Sortarray (int[] array,int start,int end)
{
if (end = = Start)
{
return;
}

int mid = (End-start)/2+start;
Sortarray (Array,start,mid);
Sortarray (Array,mid+1,end);
Merge (Array,start,mid,end);
}

public static void Main (string[] args)
{
Int[] Testarray = {0,1,2,10,18,29,14,14,13,12,18,17};
Sortarray (testarray,0,testarray.length-1);
for (int i:testarray)
{
System.out.print (i+ ",");
}
}

Merge Sort Example-java

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.