在带有二等分的数组中查找数字. C# [英] Find number in array with bisection. c#

查看:63
本文介绍了在带有二等分的数组中查找数字. C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I would  like to know how to do this with bisection. 

我需要在带有二等分的数组中找到元素,并将其索引输出到控制台.

I need to find element in array with bisection and output its index to console.

我无法找到的元素:2

示例数组:-1,0、1、2、2、3 

输出到控制台(该数组中最后一个元素的值为2的索引):4

public void Main()
    {
        int elementToFind = 2;
        int[] arrray = { -1, 0, 1, 2, 2, 3 };
    }

public static int findNumber(int el, int[] a)
        {
            if (a == null || a.Length == 0)
                return -1;

            int left = 0;
            int right = a.Length - 1;

            while (left <= right)
            {
                int middle = left + (right - left) / 2;

                if (a[middle] > el)
                {
                    right = middle - 1;
                }
                else if (a[middle] < el)
                {
                    left = middle + 1;
                }
                else
                {
                    return middle;
                }
            }
            return -1;
        }


到目前为止,我已经获得了这段代码,但是它返回了我在随机位置搜索的元素:\




I got this code so far but it returns element that I'm searching at random position :\



推荐答案

I would  like to know how to do this with bisection. 

我需要在带有二等分的数组中找到元素,并将其索引输出到控制台.

I need to find element in array with bisection and output its index to console.

我无法找到的元素:2

示例数组:-1,0、1、2、2、3 

输出到控制台(该数组中最后一个元素的值为2的索引):4

public void Main()
    {
        int elementToFind = 2;
        int[] arrray = { -1, 0, 1, 2, 2, 3 };
    }




这篇关于在带有二等分的数组中查找数字. C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆