HDOJ 2019 | 自用

该篇文章介绍了一个问题,即如何在已排序的整数序列中插入一个新的整数并保持序列有序。通过使用二分查找算法,可以高效地找到插入位置。代码示例展示了如何实现这一过程,包括读取输入、进行二分查找以及输出新序列。
摘要由CSDN通过智能技术生成

Problem Description

有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。

Input

输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。

Output

对于每个测试实例,输出插入新的元素后的数列。

Sample Input

3 3 1 2 4 0 0

Sample Output

1 2 3 4

笔记

由于是有序序列,所以考虑二分查找填空。

代码如下:

#include<iostream>
#define MAXINT 0x7fffffff
#define MININT 0x80000000
using namespace std;

int a[120];

void Insert(int, int);
int binary_search(int, int ,int);

int main(){
    int n, m, i;
    a[0] = MININT;

    while( cin >> n >> m, n != 0 || m != 0){
        for(i = 1; i <= n; ++i) cin >> a[i];
        a[n+1] = MAXINT;

        Insert(n, m);
    }
    return 0;
}

/** Binary version */
void Insert(int n, int m){
    int insertIndex = binary_search(1, n+1, m);

    for(int i = 1; i <= n; ++i){
        if(i == insertIndex) cout << m << " ";
        cout << a[i] << " ";
    }
    if(insertIndex == n+1) cout << m << " ";
    cout << endl;
}

int binary_search(int startIndex, int endIndex, int value){
    int midIndex = ( startIndex + endIndex ) / 2;

    if ( a[midIndex-1] < value && value <= a[midIndex] ) return midIndex; 
    if ( a[midIndex] < value ) return binary_search(midIndex+1, endIndex, value);
    if ( a[midIndex-1] >= value ) return binary_search(startIndex, midIndex-1, value);
    return -1;
} 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值