我该怎么做二进制搜索算法

时间:2017-04-23 06:06:52

标签: c#

对于我们班级的acedemic练习,我们需要制作一个可以执行二分查找的程序,然后显示目标的索引。这是我现在的代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Binarysearch
{
    class Program
    {
        static void Main(string[] args)
        {
            var target = 10; //Defines what the program will be searching for
            int[] array = { 2, 4, 6, 8, 10, 12, 15, 17, 19, 21, 99999 };
            var last = array.Last();
            var first = array.First();
            var mid = array[array.Length / 2];
            bool found = false;

            while (first <= last && found == false)
            {
                if (mid > target)
                {

                }
                if (mid == target)
                {
                    bool found = true;
                }
                if (mid < target)
                {

                }
            }
            if (first > last){ //If the target was not found
                Console.WriteLine("The target " + target + "was not located.");
                Console.ReadLine();
            }
            if (found == true) //If the target was found
            {
                Console.WriteLine("The target " + target + " was located at index " + mid); // Prints the final outcome.
                Console.ReadLine();
            }
        }
    }
}

所以我遇到的问题是: 我应该通过删除数组的上/下半部分来找到中间并重复吗?如果我这样做,它最终将找到目标,但我不认为它将能够找到索引,因为阵列的其余部分将被破坏。

我应该怎么做?

谢谢:p

1 个答案:

答案 0 :(得分:0)

二进制搜索负责在排序数组中查找目标的索引。它不应该以任何方式改变原始数组。

这里是用C#编写的二进制搜索的例子:

public static int BinarySearch(int[] intArr, int target)
{
    int min = 1, max = intArr.Length;
    int mid;

    while (min <= max)
    {
        mid = min + (max - min) / 2;
        if (intArr[mid] == target)
            return mid;

        else if (intArr[mid] < target)
            min = mid + 1;
        else
            max = mid - 1          
    }
    return -1; // Target was not found within the array.
}

用法:

int[] intArr = new int[] { 1, 5, 7, 9, 12, 15, 16, 17, 27, 28, 222, 235, 567, 578, 890 };
MessageBox.Show(BinarySearch(intArr, 99).ToString());