分治法

本文介绍了一种在一维有序数组中查找指定元素的算法。该算法能够返回输入元素x不在数组中时,小于x的最大元素位置及大于x的最小元素位置;若x存在于数组中,则返回x的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:假定一个已经排好顺序的一维数组,运用二分搜索算法,使得当前输入元素x不在数组中是,返回小于x的最大元素位置i和大于x的最小元素的位置j,当搜索元素在数组中,i

和j相同,均为x在数组中的位置.

算法分析:

         分治法算法:

void fenzhi(int a[10],int x)
{
       int i,flag_up,flag_down;
       int max_left,max_right,found_left,found_right;
       for(i=0;i<10;i++)
        {
            if(a[i]<x)
                max_left=i;
            else if(a[i]==x)
                found_left=i;
            else flag_down=1;
        }
        for(i=10;i>0;i--){
            if(a[i]>x)
                max_right=i;
             else if(a[i]==x)
                found_right=i;
             else flag_up=1;
        }
        if(flag_down==1){
            printf("Under Out of Index");
        }
        else if(flag_up==1){
            printf("Up Out of Index");
        }
        else{
           if(found_right!=found_left){
            printf("%d %d\n",max_left,max_right);
           }
           else
           printf("found and the place is %d\n",found_left);
        }
}

算法分析:定义一对变量:max_left和max_right分别为当x不在数组中时的左右位置;

定义一对变量:found_left和found_right分别为当x在数组中时的左右位置;

定义一对变量:flag_down和flag_up分别为当x超出我所设定的数组边界时,判断此时是为上边界越线还是下边界越线。

在代码中,首先写一个递增循环,找出三种情况:1.x未超界且x不在数组中时,x的最近左边位置max_left;2.x未超界且x在数组中时,x的左边位置found_left;3.x超界时,为下边界;

   其次写一个递减循环,找出三种情况:1.x未超界且x不在数组中时,x的最近右边位置max_right;2.x未超界且x在数组中时,x的右边位置found_right;3.x超界时,为上边界;

                                    最后就是一系列判断的代码。

完整代码:

#include<stdio.h>

void fenzhi(int a[10],int x)
{
       int i,flag_up,flag_down;
       int max_left,max_right,found_left,found_right;
       for(i=0;i<10;i++)
        {
            if(a[i]<x)
                max_left=i;
            else if(a[i]==x)
                found_left=i;
            else flag_down=1;
        }
        for(i=10;i>0;i--){
            if(a[i]>x)
                max_right=i;
             else if(a[i]==x)
                found_right=i;
             else flag_up=1;
        }
        if(flag_down==1){
            printf("Under Out of Index");
        }
        else if(flag_up==1){
            printf("Up Out of Index");
        }
        else{
           if(found_right!=found_left){
            printf("%d %d\n",max_left,max_right);
           }
           else
           printf("found and the place is %d\n",found_left);
        }
}
int main()
{
    int a[10]={1,2,3,4,5,6,7,8,10,11};
    int x;
    printf("Input the number:");
    scanf("%d",&x);
    fenzhi(a,x);
    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值