Linear search and binary search
Search unsorted data one item at a time, then halve the search space on sorted data with binary search, and use the .NET methods correctly.
Linear search: check everything
static int LinearSearch(int[] a, int target){ for (int i = 0; i < a.Length; i++) if (a[i] == target) return i; return -1; // not found}Binary search: halve the problem
static int BinarySearch(int[] a, int target){ int lo = 0, hi = a.Length - 1; // the range that may still contain target while (lo <= hi) { int mid = lo + (hi - lo) / 2; // middle of the range if (a[mid] == target) return mid; if (a[mid] < target) lo = mid + 1; // discard the left half (and mid) else hi = mid - 1; // discard the right half (and mid) } return -1; // range is empty: not found} int[] lengths = { 3, 7, 11, 15, 18, 22, 27, 31 };Console.WriteLine(BinarySearch(lengths, 22));Console.WriteLine(BinarySearch(lengths, 20));5 -1
How fast is it?
| Sorted items | Linear search (worst) | Binary search (worst) |
|---|---|---|
Binary search in .NET
Array.BinarySearch and List<T>.BinarySearch are built in. When the value is not found they return a negative number: the bitwise complement (~) of the index where it would be inserted. That is useful for inserting into a sorted list.
int[] a = { 3, 7, 11, 15 }; Console.WriteLine(Array.BinarySearch(a, 11)); // found at index 2 int r = Array.BinarySearch(a, 8);Console.WriteLine(r); // not found: negativeConsole.WriteLine(~r); // 8 would go at index 2 // Keep a List sorted while insertingvar sorted = new List<int> { 3, 7, 11, 15 };int pos = sorted.BinarySearch(8);sorted.Insert(pos >= 0 ? pos : ~pos, 8);Console.WriteLine(string.Join(", ", sorted));2 -3 2 3, 7, 8, 11, 15
Should I sort first?
HashSet<T> is even faster: O(1) per lookup.
| Situation | Best choice |
|---|---|
HashSet<T> / Dictionary<K,V> |
SearchInsert(int[] a, int target) for a sorted array with no duplicates. Return the index of target if found, otherwise the index where it would be inserted to keep the array sorted. For { 1, 3, 5, 6 }: 5 → 2, 2 → 1, 7 → 4, 0 → 0. Use binary search.
Show a hint
lo is exactly the insertion point.
Show the solution
static int SearchInsert(int[] a, int target){ int lo = 0, hi = a.Length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == target) return mid; if (a[mid] < target) lo = mid + 1; else hi = mid - 1; } return lo; // first index whose value is bigger than target} int[] a = { 1, 3, 5, 6 };foreach (int t in new[] { 5, 2, 7, 0 }) Console.Write(SearchInsert(a, t) + " ");2 1 4 0
Remember
Linear search works on any data and is O(n). Binary search needs sorted data and halves the range each step: O(log n). Use mid = lo + (hi - lo) / 2to avoid overflow..NET’s BinarySearchreturns~insertionPointwhen the value is missing.