Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class BinarySearchFindElement
- {
- static int BinarySearch(int[] array, int getIndex)
- {
- int iMin = 0;
- int iMax = array.Length - 1;
- // continue searching while [imin,imax] is not empty
- while (iMax >= iMin)
- {
- /* calculate the midpoint for roughly equal partition */
- int iMid = (iMax + iMin) / 2;
- // determine which subarray to search
- if (array[iMid] < getIndex)
- // change min index to search upper subarray
- iMin = iMid + 1;
- else if (array[iMid] > getIndex)
- // change max index to search lower subarray
- iMax = iMid - 1;
- else
- // key found at index imid
- return iMid;
- }
- // key not found
- return -1;
- }
- static void Main()
- {
- int[] myArray = { -10, -8, -3, 0, 1, 1, 2, 3, 5, 10, 10, 25, 26, 30, 31, 33, 38, 40};
- int number = 26;
- // int number = 34; // Return that the number is not found
- if (BinarySearch(myArray, number) == -1)
- {
- Console.WriteLine("The searching number \"{0}\" is not found in the array!", number);
- }
- else
- {
- Console.WriteLine("The index of number is: " + BinarySearch(myArray, number));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement