首页 > Windows开发 > 详细

C# 二分查询

时间:2016-02-17 18:41:41      阅读:314      评论:0      收藏:0      [点我收藏+]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 二分查询
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] array = { 10, 20, 50, 6, 45, 10, 33, 25, 40, 5 };

            Array.Sort(array);

            Console.Write("数组排序之后: ");
            foreach (var i in array)
            {
                Console.Write(i + ",");
            }

            Console.WriteLine();
            int a = SearchFun(array, 45);
            Console.WriteLine("找到的值:" + a);




            Console.Read();
        }

        static int SearchFun(int [] array,int value)
        {
            int mid, low, high;

            low = 0;
            high = array.Length - 1;

            while (low < high)
            {
                mid = (low + high) / 2;                 //数组从中间找
                if (array[mid] == value)
                    return array[mid];

                if (array[mid] > value)                 //数组中的值 大于 要找的值, 继续在数组下部分查询   
                    high = mid - 1;
                else
                    low = mid + 1;                      //数组中的值 大于 要找的值, 继续在数组上部分查询   
            }

            return -1;

        }

    }
}

技术分享

C# 二分查询

原文:http://www.cnblogs.com/plateFace/p/5196146.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!