Merge (merge) sort (mergesort)

Source: Internet
Author: User

// Used to count the number of test execution cycles.
Int count;
Private void button#click (Object sender, eventargs E)
{

Random ther = new random (). Next (30000 ));
List <int> Thea = new list <int> ();
Int n = 1024;
For (INT I = 1; I <= N; I ++)
{
Thea. Add (ther. Next (10000 ));
}
Count = 0;
Int [] theb = Thea. toarray ();
Mergesort (theb, 0, n-1 );
}

Private void mergesort (INT [] A, Int Is, int IE)
{

// Equal, indicating a number. A number is considered sorted.
If (is = IE)
{
Count ++;
Return;
}

// Sort the Left and Right segments by two methods
Int ie1 = (is + IE)/2;
Int is2 = ie1 + 1;
Mergesort (A, is, ie1 );
Mergesort (A, is2, ie );

// After sorting out the left and right after the merger for two sorting order segment (iS-iE1, iS2-iE) to sort out
Int I1 = is, J1 = is2; // The merge results all point to the minimum index of each segment.
// Because they are all stored in the is-> ie segment of the array, and from small to large, from left to right.
// The maximum number of organization operations is ie-is.
While (true)
{
// If the current value of the Left segment is smaller than or equal to the minimum value of the right segment, you do not need to move it. You can move the i1 pointer to the left segment to the right.
If (A [I1] <= A [J1])
{
Count ++;
I1 ++; // right shift
// Because both segments are sorted, if the left segment is sorted, the left segment does not need to be sorted.
If (I1> = J1)
{
Break;
}
}
Else
{
// If the left segment is greater than the right segment, shift is required.
// Move J1 to I1, the original I1 to the entire right of the j1-1.
Int TMP = A [I1];
A [I1] = A [J1];
For (INT b2 = J1; B2> I1 + 1; B2 --)
{
A [B2] = A [B2-1];
Count ++;
}
A [I1 + 1] = TMP;
I1 ++; J1 ++;
}
// Because both segments are sorted, if the right segment is sorted, the left segment does not need to be sorted.
If (J1> IE)
{
Break;
}
}
}

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.