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