Sort algorithm-merge sort

Source: Internet
Author: User

Merge sort:

Dividing the array to be sorted into a number of sub-arrays so that the subarray is ordered, and then the arrays are ordered, and the resulting arrays are both sorted arrays.

The code is as follows:

//Merge Sort//arrange Unsort[start,middle] and Unsort[middle] in the sort array in ordervoidMargeintUnsort[],intStartintMiddle,intend) {    intsort[Ten]; inti = Start,j = middle +1, k =start;  while(I < Middle+1&& J < end+1)    {        if(Unsort[i] <Unsort[j]) {Sort[k+ +] = unsort[i++]; }        Else{sort[k+ +] = unsort[j++]; }    }     while(I < Middle+1) {sort[k+ +] = unsort[i++]; }     while(J < end+1) {sort[k+ +] = unsort[j++]; }     for(inti = start; I < end+1; i++) {Unsort[i]=Sort[i]; }}voidMarge_sort (intUnsort[],intlenght) {    inti =0; intD =1; //The permutations are grown in 1,2,4,8, and the length of an array to be merged is greater than or equal to the length of the array, so no comparison is made.     while(d<lenght+1)    {        //The first worthy index of the first array to be compared should be within the range of the array         while(i+d-1<lenght) {            if(i+2*d-1<lenght) {Marge (unsort, I, I+d-1, i+2*d-1); I= i+2*D; }            Else{Marge (unsort, I, I+d-1, lenght-1); cout<<Endl; I=lenght; }} D=d*2; I=0; }}

Attention:

The Marge function is a function of comparing two arrays, the method of comparison is both the first value of a array and the first value of B array, if the first value of a is small, then a[0] into a temporary array c[0], and then a[1] and b[0, if b[0] small, then c[1]=b[ 0] .... And so on, the value of the remaining array is inserted at the end of the C array.

Sort algorithm-merge sort

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.