Advertisement
stefanpu

BinarySearch example

Feb 12th, 2013
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3.  
  4. namespace BinarySearchExamples
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.  
  11.             int[] binarySearchTestArray = { 1, 2, 3, 5 };
  12.  
  13.             //For return of BinarySearch method see:
  14.             //http://msdn.microsoft.com/en-us/library/w4e7fxsh.aspx
  15.  
  16.  
  17.  
  18.             //Examples of searched values that are not found.
  19.             #region
  20.             //I. Index of element that is in between the smallest and the largest item
  21.             //but not found in the list.
  22.             int searchedValue = 4;
  23.             int indexOfSearchedValue = Array.BinarySearch(binarySearchTestArray, searchedValue);
  24.  
  25.             //The index of the next larger value is 3 (11) its bitwise complement is -4.
  26.             //(Due to Two`s complement) See: http://en.wikipedia.org/wiki/Two%27s_complement
  27.             // and http://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-work
  28.             Console.WriteLine(indexOfSearchedValue);
  29.            
  30.  
  31.  
  32.             //II. Index of element that is smaller than the smallest element
  33.             searchedValue = 0;
  34.             indexOfSearchedValue = Array.BinarySearch(binarySearchTestArray, searchedValue);
  35.  
  36.             //Again the bitwise complement of first larger element is returned
  37.             Console.WriteLine(indexOfSearchedValue);
  38.  
  39.  
  40.  
  41.             //III. Index of element that is larger than the largest element
  42.             searchedValue = 454;
  43.             indexOfSearchedValue = Array.BinarySearch(binarySearchTestArray, searchedValue);
  44.  
  45.             //This time the bitwise complement of elements count is returned
  46.             //count =4 => -5
  47.             Console.WriteLine(indexOfSearchedValue);
  48.             #endregion
  49.  
  50.  
  51.  
  52.             //HOW TO FIND LARGEST THAT IS SMALLER THAN SEARCHED VALUE?
  53.             searchedValue = 4;
  54.             indexOfSearchedValue = Array.BinarySearch(binarySearchTestArray, searchedValue);
  55.  
  56.             //negate(to get index of first larger) and extract 1
  57.             indexOfSearchedValue = ~indexOfSearchedValue - 1;
  58.  
  59.             Console.WriteLine("Index of searched value: {0}",indexOfSearchedValue);
  60.  
  61.             //Note: In case searched value is found just return its index
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement