A non-recursive algorithm for merging sort

Source: Internet
Author: User

Algorithm idea:

First assume length=1; Indicates that the adjacent 2 elements are sorted first. A[0] and a[1],a[2] and a[3] ...... A[n-2] and A[n-1] (N is even hypothesis)

Then Length=2;a[0]a[1] is an ordered sequence, with a[2]a[3] to merge 2 ordered sequences.

In turn.

  voidMerge_pass (ElementType a[],elementtype temp[],intNintlength) { inti,j;  for(i=0; i<n-2*length;i+=2*length) Merge1 (A,temp,i,i+length,i+length*2-1); if(i+length<N) Merge1 (a,temp,i,i+length,n-1);//Super ErrorElse    {         for(j=i;j<n;j++) Temp[j]=A[j]; }} voidMerge_sort (ElementType a[],intN) {intlength; ElementType*Temp; Temp= (ElementType *)mallocNsizeof(ElementType)); Length=1; if(temp!=NULL) {          while(length<N) {merge_pass (a,temp,n,length); Length=length*2;             Merge_pass (temp,a,n,length); Length=length*2; }     }     Elseprintf ("error\n"); } voidMerge1 (ElementType a[],elementtype temp[],intLeft,intRight,intrightend) {    intTemp,i, Leftend,count; Leftend=right-1; Count=rightend-left+1; Temp=Left ;  while(left<=leftend&& right<=rightend) {        if(a[left]<=A[right]) Temp[temp++]=a[left++]; Elsetemp[temp++]=a[right++]; }     while(left<=leftend) Temp[temp++]=a[left++];  while(right<=rightend) Temp[temp++]=a[right++]; }

Error Analysis:

Merge1 (a,temp,i,i+length,n);
There should be n elements, and the subscript for the last element is n-1!!!!!!!!!!!!!

Non-recursive algorithm for 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.