Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that finds the index of
- * given element in a sorted array of integers
- * by using the binary search algorithm (find it in Wikipedia).
- */
- using System;
- class BinarySearch
- {
- static int BinSearch(int[] array, int key)
- {
- Array.Sort(array);
- int iMax = array.Length - 1;
- int iMin = 0;
- while (iMax >= iMin)
- {
- int iMidpoint = (iMin + iMax) / 2;
- if (array[iMidpoint] < key)
- {
- iMin = iMidpoint + 1;
- }
- else if (array[iMidpoint] > key)
- {
- iMax = iMidpoint - 1;
- }
- else
- {
- return iMidpoint;
- }
- }
- return -1;
- }
- static void Main()
- {
- Console.Write("Enter array length: ");
- int length = int.Parse(Console.ReadLine());
- int[] myArray = new int[length];
- //enter array elements
- for (int i = 0; i < myArray.Length; i++)
- {
- Console.Write("Number {0} = ", i + 1);
- myArray[i] = int.Parse(Console.ReadLine());
- }
- Console.Write("Key = ");
- int key = int.Parse(Console.ReadLine());
- Console.WriteLine("The array is sorted ! Example : 0,1,2,3,4,6,9,20...");
- Console.Write("Index of key = ");
- Console.WriteLine(BinSearch(myArray, key));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment