Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class BinarySearch //source - wikipedia
- {
- static void Main()
- {
- int[] arr = { 7, 12, 46, 2, 6, 24, 218, -5 };
- Console.Write("Choose a value from {0}:", string.Join(", ", arr));
- int value = int.Parse(Console.ReadLine());
- Array.Sort(arr);
- int minIndex = 0;
- int maxIndex = arr.Length - 1;
- while (maxIndex >= minIndex)
- {
- int midIndex = (maxIndex + minIndex) / 2;
- // determine which subarray to search
- if (arr[midIndex] < value)
- {
- // change min index to search upper subarray
- minIndex = midIndex + 1;
- }
- else if (arr[midIndex] > value)
- {
- // change max index to search lower subarray
- maxIndex = midIndex - 1;
- }
- else
- {
- value = midIndex;
- }
- }
- Console.WriteLine("Position {0} in this sorted array.", value);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement