C# 二叉查找

[code=c#]

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace BinarySearch

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] arrNum = {2,4,6,8,10,12,14};

            Console.Write(BinarySearch(arrNum, 14));

            Console.Read();

        }

 

        public static int BinarySearch(int[] a,int num)

        {

            if (a.Length <= 0)

            {

                return -2;

            }

            int startPos = 0;

            int endPos = a.Length - 1;

            int m = (startPos + endPos) / 2;

            while (startPos <= endPos)//startPos < endPos will be woring

            {

                if (num == a[m]) return m;

                if (num > a[m])

                {

                    startPos = m + 1;

                    // startPos = m; 使用这种形式不加1或者不减1,有可能出现死循环,比如获取 {2,4,6,8,10,12,14}中的14的时候,m永远为5并且为5的时候,

                    //startPos <= endPos 无法改变,导致程序进入死循环。2010年3月22日22:59:53

                }

                if (num < a[m])

                {

                    endPos = m - 1;

                    //endPos = m;

                }

                m = (startPos + endPos) / 2;

            }

            return -1;

        }

    }

}

[/code]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值