Warning! It seems that you are using Dodona within another webpage, so not everything may work properly. Let your teacher know so that he can solve the problem by adjusting a setting in the learning environment. In the meantime, you can click this link to open Dodona in a new window.
Warning! The page was not fully loaded, probably because of a network issue. It could be that not all functionalities work as expected. Please try reloading the page.
Binair zoeken — oefening
Sign in to test your solution.
// De gesorteerde lijst en de in- en uitvoer zijn al voorzien.
// Jij hoeft enkel de functie IndexInLijst hieronder in te vullen.
int[] lijst = new int[]
{
5, 6, 12, 19, 23, 26, 31, 33, 40, 44, 49, 56, 60, 65, 72, 76,
78, 79, 85, 86, 89, 95, 100, 109, 111, 120, 123, 125, 134, 143, 152, 157,
165, 174, 179, 180, 188, 189, 198, 207, 213, 216, 223, 229, 237, 243, 244, 250,
251, 257, 266, 270, 275, 282, 286, 291, 294, 298, 306, 308, 315, 316, 317, 324,
328, 330, 332, 336, 340, 345, 347, 353, 359, 363, 370, 379, 387, 396, 403, 406,
410, 411, 418, 421, 429, 432, 439, 443, 451, 453, 460, 461, 465, 473, 480, 489,
494, 501, 504, 510, 516, 518, 519, 524, 532, 540, 544, 549, 554, 559, 562, 566,
571, 580, 583, 585, 593, 600, 608, 616, 620, 627, 632, 634, 641, 642, 651, 654,
655, 659, 667, 674, 681, 686, 688, 692, 695, 703, 705, 710, 716, 718, 722, 724,
732, 735, 737, 738, 746, 752, 760, 762, 764, 767, 769, 774, 775, 782, 790, 799,
807, 810, 814, 819, 827, 835, 839, 842, 844, 852, 858, 860, 869, 875, 878, 882,
886, 894, 895, 899, 908, 914, 921, 927, 931, 934, 943, 952, 953, 954, 959, 963,
964, 965, 971, 976, 981, 987, 991, 998
};
// Lees het gezochte getal en druk het resultaat af. Dit is al voorzien:
int gezocht = Convert.ToInt32(Console.ReadLine());
int index = IndexInLijst(lijst, gezocht);
if (index < 0)
{
Console.WriteLine(gezocht + " zit niet in de lijst");
}
else
{
Console.WriteLine(gezocht + " staat op index " + index);
}
// Geef de (nul-gebaseerde) index terug van getal in getallen,
// of -1 als getal niet in de lijst zit. Gebruik binair zoeken.
int IndexInLijst(int[] getallen, int getal)
{
// TODO: implementeer hier binair zoeken.
// Tip: hou een linkergrens en een rechtergrens bij, bereken telkens
// het midden met een gehele deling, en gooi de helft weg waarin
// getal niet kan zitten.
return -1; // pas dit aan
}