Linier and binary search Flashcards
How does linear search work?
1) Start with the first element
2) Compare the current element with the search term
3) If they match - report found and stop the search
4) Otherwise set the current element to be the next element
5) Repeat from step until Found or end of array reached
What are the pros and cons of Linear search
+straight-forward to program
+data doesn’t not need to be sorted
+fine for a small dataset
-Inefficient with large datasets
How does a binary search work?
1) calculate the midpoint
2) Compare item at midpoint with search
3) if equal then stop search and report found
4) if search < item at midpoint then highPtr -mid-1
5) if search > item at midpoint then lowPtr =mid+1
6) repeat from step 1 while lowPtr <=highPtr and not found
pros and cons of binary search
+ fewer comparisons makes this earch faster than linear
- trickier to program
- dataset must be ordered