viernes, 17 de agosto de 2012

busqueda binaria en c sharp


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int[] vector = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
            int longitud = vector.Length;
            int datoabuscar = int.Parse(textBox1.Text);          
            int posicion = buscador(vector, datoabuscar);
            if (vector[posicion] == datoabuscar)
                MessageBox.Show("el dato esta en la posicion" + posicion);
            else
                MessageBox.Show("dato no encontrado");
           

        }
        static public int buscador(int[] vec, int dato)
        {
            int limiteSuperior = vec.Length -1;
            int LimiteInferior = 0;
            int medio;
            while (LimiteInferior < limiteSuperior)
            {
               medio = (LimiteInferior + limiteSuperior)/2;
               if (vec[medio] == dato)
               {

                   return (medio);
                 
               }
               else if (vec[medio] > dato)
               {
                   limiteSuperior = medio - 1;
               }
               else
                   LimiteInferior = medio + 1;


             }
            return -1;

        }
    }
}

4 comentarios: