6-15 Iterative Mergesort(25 分)

6-15 Iterative Mergesort(25 分)

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 sortedN is the number of elements in the list and length is the length of the sublists.

Sample program of judge:

#include 

#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

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 Ptr3 = 0;
int i;
for (i = 0; i <= N-2*length; i=i+2*length) {
int Ptr1 = i, Ptr2 = i + length;
while (Ptr1 < i + length && Ptr2 < i + 2 * length) {
if (list[Ptr1] < list[Ptr2])
sorted[Ptr3++] = list[Ptr1++];
else
sorted[Ptr3++] = list[Ptr2++];
}
if (Ptr1 == i + length && Ptr2 != i + 2 * length)
while (Ptr2 sorted[Ptr3++] = list[Ptr2++];
if (Ptr2 == i + 2 * length && Ptr1 != i + length)
while (Ptr1 sorted[Ptr3++] = list[Ptr1++];
}
if (i + length < N) {
int Ptr1 = i, Ptr2 = i + length;
while (Ptr1 < i + length && Ptr2 < N) {
if (list[Ptr1] < list[Ptr2])
sorted[Ptr3++] = list[Ptr1++];
else
sorted[Ptr3++] = list[Ptr2++];
}
if (Ptr1 == i + length && Ptr2 != N)
while (Ptr2 < i + 2 * length)
sorted[Ptr3++] = list[Ptr2++];
if (Ptr2 == N && Ptr1 != i + length)
while (Ptr1 < i + length)
sorted[Ptr3++] = list[Ptr1++];
}
else
for (int j = i; j < N; j++)
sorted[j] = list[j];
}

你可能感兴趣的:(PTA习题记录)