Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace _11.BinarySearch
- {
- class BinarySearch
- {
- static int BinaryIndexFinder(int[] array, int key)
- {
- int downBorder = 0;
- int upBorder = array.Length - 1;
- while (true)
- {
- int marker = (upBorder + downBorder) / 2;
- if (marker == downBorder)
- {
- if (key == array[upBorder])
- {
- return upBorder;
- }
- else if (key == array[downBorder])
- {
- return downBorder;
- }
- else
- {
- break;
- }
- }
- if (key > array[marker])
- {
- downBorder = marker + 1;
- }
- else if (key < array[marker])
- {
- upBorder = marker - 1;
- }
- else
- {
- return marker;
- }
- }
- return -1;
- }
- static void Main(string[] args)
- {
- int[] array = {-10, -6, -3, -1, 1, 3, 5, 10, 12, 13, 18, 21};
- Array.Sort(array);
- Console.Write("Enter a number: ");
- int number = int.Parse(Console.ReadLine());
- int index = BinaryIndexFinder(array, number);
- if (index == -1)
- {
- Console.WriteLine("Number is not find in the array");
- }
- else
- {
- Console.WriteLine("Index of number: {0}", index);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement