vsvub

csharp-search-binary

Jun 24th, 2014
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.85 KB | None | 0 0
  1. public static class ListExtensions
  2. {
  3.     static int Find<TListInt>(this TListInt list, int first, int last, int value)
  4.         where TListInt : IList<int>
  5.     {
  6.         int diff = ( last - first );
  7.         if (diff == 0)
  8.         {
  9.             if (list[first] == value)
  10.             {
  11.                 return last;
  12.             }
  13.             return -1;
  14.         }
  15.         int mid = first + ( diff / 2 );
  16.         int midValue = list[mid];
  17.         if (midValue == value)
  18.         {
  19.             return mid;
  20.         }
  21.         else if (midValue > value)
  22.         {
  23.             if (--mid < first)
  24.             {
  25.                 return -1;
  26.             }
  27.             return list.Find(first, mid, value);           
  28.         }
  29.         else
  30.         {
  31.             if (++mid > last)
  32.             {
  33.                 return -1;
  34.             }
  35.             return list.Find(mid, last, value);
  36.         }
  37.     }
  38.  
  39.     public static int Find<TListInt>(this TListInt list, int value)
  40.         where TListInt : IList<int>
  41.     {
  42.         if (list != null && list.Count > 0)
  43.         {
  44.             return list.Find(0, list.Count - 1, value);
  45.         }
  46.         return -1;
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment