Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- namespace BinarySearchExamples
- {
- class Program
- {
- static void Main(string[] args)
- {
- int[] binarySearchTestArray = { 1, 2, 3, 5 };
- //For return of BinarySearch method see:
- //http://msdn.microsoft.com/en-us/library/w4e7fxsh.aspx
- //Examples of searched values that are not found.
- #region
- //I. Index of element that is in between the smallest and the largest item
- //but not found in the list.
- int searchedValue = 4;
- int indexOfSearchedValue = Array.BinarySearch(binarySearchTestArray, searchedValue);
- //The index of the next larger value is 3 (11) its bitwise complement is -4.
- //(Due to Two`s complement) See: http://en.wikipedia.org/wiki/Two%27s_complement
- // and http://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-work
- Console.WriteLine(indexOfSearchedValue);
- //II. Index of element that is smaller than the smallest element
- searchedValue = 0;
- indexOfSearchedValue = Array.BinarySearch(binarySearchTestArray, searchedValue);
- //Again the bitwise complement of first larger element is returned
- Console.WriteLine(indexOfSearchedValue);
- //III. Index of element that is larger than the largest element
- searchedValue = 454;
- indexOfSearchedValue = Array.BinarySearch(binarySearchTestArray, searchedValue);
- //This time the bitwise complement of elements count is returned
- //count =4 => -5
- Console.WriteLine(indexOfSearchedValue);
- #endregion
- //HOW TO FIND LARGEST THAT IS SMALLER THAN SEARCHED VALUE?
- searchedValue = 4;
- indexOfSearchedValue = Array.BinarySearch(binarySearchTestArray, searchedValue);
- //negate(to get index of first larger) and extract 1
- indexOfSearchedValue = ~indexOfSearchedValue - 1;
- Console.WriteLine("Index of searched value: {0}",indexOfSearchedValue);
- //Note: In case searched value is found just return its index
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement