All lessons

6. Searching

Linear search

0 of 5 activities0%

Reading 1

Simple and general

Open

Linear search checks each element until it finds the target or runs out.

Time O(n), works on unsorted data. Fine for small n; binary search needs sorted order.

int find(vector<int>& a, int t){
  for(int i=0;i<(int)a.size();i++)
    if(a[i]==t) return i;
  return -1;
}

Check 2

Requires sorted?

Open

Linear search requires a sorted array:

Fill in 3

Miss

Open

A common return value meaning not found is

Try it 4

Find 7

Open

Index of 7.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Find index

Open

Read n, n ints, then t. Print the first index of t (0-based), or -1.

main.cpp
Loading editor…