简体   繁体   中英

How should i go about a binary search algorithm

For an acedemic exercise with our class, we need to make a program that can perform a binary search, and then display the index of the target. Here is my code right now:

 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();
            }
        }
    }
}

So the problem i am running into: Should i do this by deleting the upper / lower half of the array, finding the middle and repeating? if i do this, it will eventually find the target, but i dont think it will be able to find the index as the rest of the array would be ruined.

How should i go about this?

Thanks :p

A Binary Search is in charge of finding the index of your target within a sorted array. It is not supposed to alter the original array in any sort of way.

Here's an examply of a Binary Search written in 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.
}

Usage:

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM