二分查找面试题

昨天面试有一个二分查找的题目,题目大致是有随机生成100个整数,用二分查找法找出一个数字在这个100个数中的位置。当时二选一没有选择这道题目,今天早上起床做了一遍,以下是大致代码:

    protected void Page_Load(object sender, EventArgs e)

    {

        int[] thisdata = data();

        foreach(int a in thisdata)

        {

            Response.Write(a + " ");   

        }

        Response.Write("<br/>");

        thisdata = sorted(thisdata);

        foreach (int a in thisdata)

        {

            Response.Write(a + " ");

        }

        Response.Write("<br/>");

 

        int result = BinarySearch(thisdata, 0, thisdata.Length - 1, 10);

        Response.Write(result);

    }

 

    /// <summary>

    /// 10个随机数组生成

    /// </summary>

    /// <returns></returns>

    private int[] data()

    {

        Random rd = new Random();

        int[] result = new int[10];

        for (int i = 0; i < result.Length; i++)

        {

            result[i] = rd.Next(15);

        }

 

        return result;

    }

 

    /// <summary>

    /// 对数组data进行由小到大排序

    /// </summary>

    /// <param name="data"></param>

    /// <returns></returns>

    private int[] sorted(int[] data)

    {

        int temp=0;

        for (int i = 0; i < data.Length; i++)

        {

            for (int j = i + 1; j < data.Length; j++)

            {

                if (data[j] < data[i])

                {

                    temp = data[i];

                    data[i] = data[j];

                    data[j] = temp;

                }

            }

        }

        return data;

    }

 

    /// <summary>

    /// 二分查找

    /// </summary>

    /// <param name="data"></param>

    /// <param name="start"></param>

    /// <param name="end"></param>

    /// <param name="key"></param>

    /// <returns></returns>

    private int BinarySearch(int[] data, int start, int end, int key)

    {

        int result = -1;

        if (start >= end && data[end] == key)

        {

            result = end;

        }

        else if (start == end && data[end] != key)

        {

            return result;

        }

        else

        {

            int newend = (start + end) / 2;

            if (data[newend] == key)

                result = newend;

            else

                result = ((key < data[newend]) ? BinarySearch(data, start, newend - 1, key) : BinarySearch(data, newend + 1, end, key));

        }

 

        return result;

    }

 

阅读更多
换一批

没有更多推荐了,返回首页