4-1 Iterative Mergesort (9分)
How would you implement mergesort without using recursion?
The idea of iterative mergesort is to start from N sorted sublists of length 1, and each time to merge a pair of adjacent sublists until one sorted list is obtained. You are supposed to implement the key function of merging.
Format of functions:
void merge_pass( ElementType list[], ElementType sorted[], int N, int length );
The function merge_pass
performs one pass of the merge sort that merges adjacent pairs of sublists from list
into sorted
. N
is the number of elements in the list
and length
is the length of the sublists.
Sample program of judge:
#include <stdio.h>
#define ElementType int
#define MAXN 100
void merge_pass( ElementType list[], ElementType sorted[], int N, int length );
void output( ElementType list[], int N )
{
int i;
for (i=0; i<N; i++) printf("%d ", list[i]);
printf("\n");
}
void merge_sort( ElementType list[], int N )
{
ElementType extra[MAXN]; /* the extra space required */
int length = 1; /* current length of sublist being merged */
while( length < N ) {
merge_pass( list, extra, N, length ); /* merge list into extra */
output( extra, N );
length *= 2;
merge_pass( extra, list, N, length ); /* merge extra back to list */
output( list, N );
length *= 2;
}
}
int main()
{
int N, i;
ElementType A[MAXN];
scanf("%d", &N);
for (i=0; i<N; i++) scanf("%d", &A[i]);
merge_sort(A, N);
output(A, N);
return 0;
}
/* Your function will be put here */
Sample Input:
10
8 7 9 2 3 5 1 6 4 0
Sample Output:
7 8 2 9 3 5 1 6 0 4
2 7 8 9 1 3 5 6 0 4
1 2 3 5 6 7 8 9 0 4
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
void merge_pass( ElementType list[], ElementType sorted[], int N, int length ){ int temp; if(length>N) return ; int i,j=0,count1=0,count2=0; int M=N; count1=0; count2=length; int start,end; int t1,t2; //printf("%d %d %d\n",count2,length,N); for(i=0;i<(N-1)/(2*length)+1;i++){ t1=0;t2=0; if(i!=(N-1)/(2*length)){ start=i*length*2; end=start+length; while(t1+t2!=2*length){ if((list[t1+start]<=list[t2+end]||t2==length)&&t1<length){ sorted[j++]=list[start+t1++]; } if((list[t1+start]>=list[t2+end]||t1==length)&&t2<length){ sorted[j++]=list[end+t2++]; } } } else{ if((N-1)%(2*length)+1<=length){ while(j++<N) sorted[j-1]=list[j-1]; } else{ start=N-(N-1)%(2*length)-1; end=start+length; while(t1+t2!=N-start){ if((list[t1+start]<=list[t2+end]||t2==N-end)&&t1<length){ sorted[j++]=list[start+t1++]; } if((list[t1+start]>=list[t2+end]||t1==length)&&t2<N-end){ sorted[j++]=list[end+t2++]; } } } } } }
感想:最重要的一点,理解题意,就算最后剩余的个数不足以完成归并排序,也要强行归并起来!!!不然最后一个点过不了