/ / ¿Cómo debo utilizar un algoritmo de búsqueda binaria? C #

¿Cómo debo ir sobre un algoritmo de búsqueda binario - c #

Para un ejercicio académico con nuestra clase, necesitamos hacer un programa que pueda realizar una búsqueda binaria y luego mostrar el índice del objetivo. Aquí está mi código en este momento:

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

Entonces, el problema con el que me encuentro: ¿Debo hacer esto eliminando la mitad superior / inferior de la matriz, encontrando el medio y repitiendo? si hago esto, eventualmente encontrará el objetivo, pero no creo que pueda encontrar el índice ya que el resto de la matriz se arruinará.

¿Cómo debo hacer esto?

Gracias p

Respuestas

0 para la respuesta № 1

Una búsqueda binaria se encarga de encontrar el índice de su objetivo dentro de una matriz ordenada. No se supone que altere la matriz original de ninguna manera.

Aquí hay un ejemplo de una búsqueda binaria escrita en 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.
}

Uso:

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