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 listinto sortedN 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

解答

这题有一个要注意的地方,就是每次归并最后剩下的数列长记为x,如果x <= length的话,就不需要归并了,直接赋值,如果x > length的话,就是一个长为length的子列和一个长为x - length的子列归并。

void merge_pass( ElementType list[], ElementType sorted[], int N, int length ){
    ;

    ; i < N; i += length * ){
         < N){
            j = i;
            k = j + length;
             * length){
                if(list[j] > list[k]){
                    sorted[index++] = list[k++];
                }
                else{
                    sorted[index++] = list[j++];
                }
            }
            while(j < i + length){
                sorted[index++] = list[j++];
            }
             * length){
                sorted[index++] = list[k++];
            }
        }
        else if(N - i > length){
            j = i;
            k = j + length;
            while(j < i + length&&k < N){
                if(list[j] > list[k]){
                    sorted[index++] = list[k++];
                }
                else{
                    sorted[index++] = list[j++];
                }
            }
            while(j < i + length){
                sorted[index++] = list[j++];
            }
            while(k < N){
                sorted[index++] = list[k++];
            }
        }
        else{
            j = i;
            while(j < N){
                sorted[index++] = list[j++];
            }
        }
    }
}

PTA Iterative Mergesort的更多相关文章

  1. java.util.List

    /* * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETA ...

  2. Timsort 算法

    转载自:http://blog.csdn.net/yangzhongblog/article/details/8184707 Timsort是结合了合并排序(merge sort)和插入排序(inse ...

  3. Java基础-集合框架-ArrayList源码分析

    一.JDK中ArrayList是如何实现的 1.先看下ArrayList从上而下的层次图: 说明: 从图中可以看出,ArrayList只是最下层的实现类,集合的规则和扩展都是AbstractList. ...

  4. TimSort Java源码个人解读

    /*JDK 1.8 */ package java.util; /** * A stable, adaptive, iterative mergesort that requires far fewe ...

  5. Collection接口的子接口——List接口

    https://docs.oracle.com/javase/8/docs/api/java/util/List.html public interface List<E> extends ...

  6. Java-Class-I:java.util.List

    ylbtech-Java-Class-I:java.util.List 1.返回顶部 1.1.import java.util.ArrayList;import java.util.List; 1.2 ...

  7. Java的集合(一)

    转载:https://blog.csdn.net/hacker_zhidian/article/details/80590428 Java集合概况就三个:List.set和map list(Array ...

  8. Iterative (non-recursive) Merge Sort

    An iterative way of writing merge sort: #include <iostream> using namespace std; void merge(in ...

  9. PTA 09-排序2 Insert or Merge (25分)

    题目地址 https://pta.patest.cn/pta/test/16/exam/4/question/675 5-13 Insert or Merge   (25分) According to ...

随机推荐

  1. 用直接路径(direct-path)insert提升性能的两种方法

    1.传统串行insert方式 常见的insert方式有两种: (1) insert into table_name values(....) (2) insert into target_table ...

  2. oracle并发请求异常,运行时间超长(一般情况下锁表)

    1.如果前台无法取消请求出现错误: 则后台更新 update fnd_concurrent_requests    set status_code = 'X', phase_code = 'C'  w ...

  3. Java Docs

    1 Java Docs on Oracle:   1.1 Online(EN): JavaSE6  http://docs.oracle.com/javase/6/docs/api/index.htm ...

  4. 根据不同分辨率加载不同 css 样芪表

    <script language=javascript> <!-- if (screen.width == 800) { document.write('<link rel=s ...

  5. 针对APP的测试过程和重点关注内容,做以下梳理和总结

    转载自金阳光测试:http://blog.sina.com.cn/s/blog_12df1b9e60102vy57.html   1. 首先是测试资源确认及准备 (1)产品需求文档.产品原型图.接口说 ...

  6. subline text3 删除行 快捷键设置

    打开 首选项-->按键绑定 { "keys": ["ctrl+shift+k"], "command": "run_macr ...

  7. 解决CentOS无法解析域名的问题

    用SecureCRT连接到CentOS上,发现ping IP通,ping地址不同 [root@zyt-ceshi2 ~]# ping www.baidu.comping: unknown host w ...

  8. NoSQL学习——MongoDB

    MongoDB作为一款文档数据库,支持分片存储,scale-out,集群自动切换,下面将粗略的配置步骤总结如下: 几个重要概念: 数据库:集合--记录--游标(查询时标记序号) sharding分片: ...

  9. Centos下安装Redis

    转自:http://nnzhp.cn/article/9/ 遇到问题,安装后并启动,redis-cli报错:Could not connect to Redis at 127.0.0.1:6379: ...

  10. websql的添加和查询

    openDatabase 我们可以使用这样简单的一条语句,创建或打开一个本地的数据库对象 var db = openDatabase('testDB', '1.0', 'Test DB', 2 * 1 ...