Kod: Zaznacz cały
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace wyszukiwanie_bnarne
{
class Program
{
static void sortuj(int[] tab, int lewy, int prawy)
{
int l, p, x, pom;
l = lewy;
p = prawy;
x = tab[(l + p) / 2];
do
{
while (tab[l] < x)
{
l = l + 1;
}
while (tab[p] > x)
{
p = p - 1;
}
if (l <= p)
{
pom = tab[l];
tab[l] = tab[p];
tab[p] = pom;
l = l + 1;
p = p - 1;
}
}
while (l <= p);
if (lewy < p)
{
sortuj(tab, lewy, p);
}
if (l < prawy)
{
sortuj(tab, l, prawy);
}
}
static void Main(string[] args)
{
int n, w, i,pocz,kon,sr,poz=0;
Console.WriteLine("Spośrod ilu liczb wybieramy? ");
n = Convert.ToInt32(Console.ReadLine());
kon = n - 1; pocz = 0;
int[] tab = new int[n];
Random generator = new Random();
Console.WriteLine("Tablica: ");
for (i = 0; i < n; i++)
{
tab[i] = generator.Next(0, n+10);
Console.Write("{0}, ", tab[i]);
}
sortuj(tab, 0, n - 1);
Console.WriteLine("");
Console.WriteLine("Tablica po posortowaniu");
for (i = 0; i < n; i++) Console.Write("{0}, ", tab[i]);
Console.WriteLine("");
Console.WriteLine("Jakiego elementu szukamy? ");
w = Convert.ToInt32(Console.ReadLine());
while (pocz <= kon)
{
sr = (pocz + kon) / 2;
if (tab[sr] < w)
{
pocz = sr + 1;
}
if (tab[sr] == w)
{
poz = sr;
break;
}
if (tab[sr] > w)
{
kon = sr - 1;
}
}
if (poz == n + 1)
{
Console.WriteLine("Element {0} nie występuje w tablicy ", w);
}
else
{
Console.WriteLine("Elwment {0} występuje w tablicy na {1} miejscu ", w, poz+1);
}
Console.ReadKey();
}
}
}
zastosowałam sortowanie szybkie