C# 二叉查找

来源:互联网 发布:网络剧十宗罪疑点 编辑:程序博客网 时间:2024/05/29 19:16

[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]

原创粉丝点击