"Algorithm" merge sort

Source: Internet
Author: User

Tag:c    algorithm    c language     merge sort    

#include <stdio. H> #include <stdlib. H>void mergepass (int *ar,int *pr,int s,int size), void merge (int *ar,int *pr,int l,int m,int R), void mergesort (int *ar,i        NT size)//merge sort {int *pr= (int *) malloc (sizeof (int) *size);  Dynamically opens a new array of array sizes to sort int s=1;      while (s<size) {mergepass (ar,pr,s,size); Executes two mergerpass functions in a while, in order to execute the loop so that the sorted elements can be saved to the original array s+=s;mergepass (pr,ar,s,size); s+=s;}                  Free (PR); function to release memory to avoid memory leaks}void mergepass (int *ar,int *pr,int s,int size)//function is the meaning of merging adjacent sub-arrays of the given size s {int i=0,j=0;while (i <= size-2 *S)//Ensure that the number of remaining unsorted elements is less than 2*s {merge (ar,pr,i,i+s-1,i+2*s-1); i=i+2*s;} if (i+s<size)//Give I plus s is still less than the total length, stating that the number of elements after I is greater than or equal to s (subscript starting from 0), so sortable {merge (ar,pr,i,i+s-1,size-1);} else for (j=i;j<size;j++)//less than S element, save directly to target array {pr[j]=ar[j];}} void merge (int *ar,int *pr,int l,int m,int R)//function means to merge ar[l]-ar[m] and Ar[m+1]-ar[r] two contiguous sub-arrays into the PR array in the order of size {int i=l,j=m+1,k =l,t=0;while (i<=m && j<=r)//compare to target array. {if (ar[i]<ar[j])//by Small toLarge order Pr[k++]=ar[i++];else pr[k++]=ar[j++];} if (i>m)//process an unspecified element for (t=j;t<=r;t++) Pr[k++]=ar[t];else for (t=i;t<=m;t++) pr[k++]=ar[t];} int main () {int Ar[]={2,4,1,8,6,7,5,9,10,3};int i;mergesort (ar,sizeof (AR)/sizeof (*ar)); for (i=0;i<sizeof (AR)/ sizeof (*ar); i++) {printf ("%d", Ar[i]);} Puts ("");}

"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.