注册 登录
编程论坛 ASP.NET技术论坛

二分运算法

misswang 发布于 2010-07-15 21:12, 584 次点击
用所学过的语言描述一下二分运算法
思路:(判断一个有序排列的数组中是否存在所要的那个数)
5 回复
#2
冰镇柠檬汁儿2010-07-15 23:36
using System;
using System.Collections.Generic;
using System.Text;
using ConsoleApplication2;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] iArrary = new int[] { 1, 5, 13, 6, 10, 55, 99, 2, 87, 12, 34, 75, 33, 47, 45 };

            //注意:这里的SelectionSorter是选择排序的类,下面一句的作用是先把输入数据作升序排列。

            //SelectionSorter类的代码参照文章五种常用的排序算法及对应的C#代码,我通过using ConsoleApplication2直接引用包含这个类的dll.

            SelectionSorter.Sort(iArrary);

            Console.WriteLine("Please input target number!");
            int target = Convert.ToInt32(Console.ReadLine());
            int low = 0;
            int high = iArrary.Length - 1;
            while (low <= high)
            {
                int mid = (low + high) / 2;
                if (target == iArrary[mid])
                {
                    mid++;
                    Console.WriteLine("Target number is at " + mid);
                    Console.ReadKey();
                    return;
                }
                else if (target < iArrary[mid])
                {
                    high = mid - 1;
                }
                else
                {
                    low = mid + 1;
                }
            }
            Console.WriteLine("Target number is out of array!");
            Console.ReadKey();
        }
    }
}
#3
misswang2010-07-16 14:50
...
#4
冰镇柠檬汁儿2010-07-16 22:24
别忘了结贴
#5
misswang2010-07-20 15:12
分儿都给你算了....哼
#6
冰镇柠檬汁儿2010-07-20 16:50
别生气啊
1