<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. DSA
  3. Searching and sorting
All lessons in this course

Lesson 12 of 50 13 minIntermediate

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.

Searching (“is this value here, and where?”) is one of the most common things programs do. There are two basic strategies, and which one you can use depends on one question: is the data sorted?

Linear search: check everything

Look at each element in turn until you find the target or run out of elements. It works on any data, sorted or not.

LinearSearch.cs
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}

Best case 1 check, worst case n checks: O(n). For a few hundred items, or a search you do only once, this is perfectly fine and the simplest correct answer.

Binary search: halve the problem

If the array is sorted, you can do far better. Look at the middle element. If it is the target, done. If the target is bigger, it can only be in the right half; if smaller, only in the left half. Throw the other half away and repeat. Like looking up a word in a dictionary: you never read every page.

Interactive

Binary search, step by step

Each check looks at the middle of the range that is still possible and throws away the half that cannot contain the target.

Checks: 0 · linear search would need 12
Looking for 51. The whole array (index 0 to 15) is still possible.
BinarySearch.cs
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));
Output
5
-1

How fast is it?

Every check halves the remaining range. Starting from n items, after k checks about n / 2ᵏ remain, so at most about log₂ n + 1 checks are needed: O(log n).

Sorted itemsLinear search (worst)Binary search (worst)
1,0001,000 checks10 checks
1,000,0001,000,000 checks20 checks
1,000,000,0001,000,000,000 checks30 checks

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.

DotNetBinarySearch.cs
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));
Output
2
-3
2
3, 7, 8, 11, 15

Should I sort first?

Sorting costs O(n log n). For one search, a linear search (O(n)) is cheaper. If you search many times in data that does not change, sort once and every search becomes O(log n). If you only need “is it there?” and never need order, a HashSet<T> is even faster: O(1) per lookup.

SituationBest choice
Small or unsorted data, few searchesLinear search
Sorted data, many searches, need order or rangesBinary search
Only “contains?” or lookup by keyHashSet<T> / Dictionary<K,V>
Quick check

Binary search on 64 sorted items: at most how many checks?

Quick check

Array.BinarySearch(a, 50) returns -5. What does it mean?

Practice

Write 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

Run the normal binary search. When the loop ends without finding the target, lo is exactly the insertion point.

Show the solution
Solution.cs
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) + " ");
Output
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) / 2 to avoid overflow.
  • .NET’s BinarySearch returns ~insertionPoint when the value is missing.
0 of 50 lessons completed