⚡0 XP🔥0

Arrays, Linear Search and Binary Search

Lesson 2 of 7 ⏱ 5 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs C++

How arrays sit in memory, vector basics, linear search, binary search on sorted data (iterative and with the STL), and the two-pointer technique.

Arrays in memory#

An array stores elements of the same type in one continuous block of memory. The address of element i is start + i × size, so reading or writing a[i] is O(1) - instant, whatever the size.

index:    0     1     2     3     4
value:  [ 12 ][ 45 ][  7 ][ 89 ][ 23 ]
address: 1000  1004  1008  1012  1016   (4-byte ints)
Operation Array / vector
read / write a[i] O(1)
add at the end (push_back) O(1) on average
insert / delete in the middle O(n) - elements must shift
search an unsorted array O(n)
search a sorted array O(log n) with binary search

In C++ we usually use std::vector - a resizable array.

▶ Try it YourselfC++
Ctrl + Enter to run
Output
size = 6, first = 72, last = 64
72 100 95 58 88 64 

Linear search - O(n)#

Check items one by one. Works on any array, sorted or not.

▶ Try it YourselfC++
Ctrl + Enter to run
Output
3
-1

Binary search - O(log n)#

On sorted data, look at the middle element. If the target is bigger, throw away the left half; if smaller, throw away the right half. Repeat.

InteractiveBinary search, step by step

Pick a target and watch the range shrink by half each step.

हिंदी में समझें

Binary search वैसा ही है जैसे dictionary में शब्द ढूंढना - आप बीच का पन्ना खोलते हैं, देखते हैं शब्द आगे है या पीछे, और आधी किताब छोड़ देते हैं। हर कदम पर आधा हिस्सा हट जाता है, इसलिए 10 लाख शब्दों में भी लगभग 20 कदम में शब्द मिल जाता है। शर्त एक ही है - data sorted होना चाहिए।

▶ Try it YourselfC++
Ctrl + Enter to run
Output
step 1: low=0 high=9 mid=4 a[mid]=25
step 2: low=5 high=9 mid=7 a[mid]=58
found at index 7
Common Mistake

Classic bugs: while (low < high) (misses the last element), low = mid instead of mid + 1 (infinite loop), and running binary search on unsorted data.

Binary search with the STL#

#include <algorithm>
bool present = binary_search(a.begin(), a.end(), 58);       // true / false
auto it = lower_bound(a.begin(), a.end(), 50);              // first element >= 50
int index = it - a.begin();                                 // 7 (value 58)

The two-pointer technique#

On a sorted array, two indices moving towards each other solve many problems in O(n) instead of O(n²) - pair sum, removing duplicates, reversing, merging.

▶ Try it YourselfC++
Ctrl + Enter to run
Output
6 5 4 3 2 1 

Summary#

  • Arrays: O(1) access by index, O(n) insert/delete in the middle.
  • Linear search O(n) works anywhere; binary search O(log n) needs sorted data.
  • mid = low + (high - low) / 2; update with mid + 1 / mid - 1.
  • STL: binary_search, lower_bound, upper_bound.
  • Two pointers turn many O(n²) pair problems into O(n).

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Binary search

Complete binarySearch so it returns the index of target in the sorted vector, or -1 if it is not present. Do it without the STL (write the loop yourself). The program must print:

45 found at index 6
7 found at index 1
50 found at index -1
Expected output:
45 found at index 6
7 found at index 1
50 found at index -1
2

Pair with the given sum

The prices are sorted. Use two pointers to find two different items whose prices add up exactly to the budget 100. Print them as 27 + 73 = 100. If no pair exists print No pair.

Expected output:
27 + 73 = 100

Quick Quiz

Q1.

What must be true before you can use binary search?

Q2.

Binary search on 1,000 sorted items needs at most about how many comparisons?

Q3.

Why write mid = low + (high - low) / 2 instead of (low + high) / 2?

Q4.

Accessing a[i] in an array takes...

Q5.

To find a pair with a given sum in a sorted array, the two-pointer method takes...