All lessonsOpen Open Open Open Open
6. Searching
Linear search
0 of 5 activities0%
Reading 1
Simple and general
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?
Linear search requires a sorted array:
Fill in 3
Miss
Try it 4
Find 7
Index of 7.
main.cpp
Loading editor…
Output will appear here.
Assignment 5
Find index
Read n, n ints, then t. Print the first index of t (0-based), or -1.
main.cpp
Loading editor…