Lec 3- Searching
Lec 3- Searching
CSC - 220
Lecture 3
Searching Algorithms
Head
35 42 12 5 \\
12 Found!
Searching in an Unordered Collection
Head
35 42 12 5 \\
13 Not Found!
Searching Algorithms
• Looking up a phone number, accessing a website and
checking a word’s definition in a dictionary all involve
searching through large amounts of data.
• Searching algorithms all accomplish the same goal,
finding an element that matches a given search key
• The major difference is the amount of effort they
require to complete the search.
• One way to describe this effort is with Big O notation.
– For searching and sorting algorithms, this is particularly
dependent on the number of data elements.
Linear (Sequential) Search
• Linear search is a very basic and simple algorithm
• We search an element or value in a given array
by traversing the array from the starting till
– desired element or
– value is found.
• It compares the required element with all the
elements of the array and when the element is
matched successfully,
– It returns the index of the element in the array, else
– it return -1. (If unsuccessful)
Linear Search
• To determine that a value is not in the array,
– the program must compare the search key to
every array element.
• Linear search works well for
– Small or
– Unsorted arrays.
• However, for large arrays, linear search is
inefficient.
Note: linear search can be applied to both sorted and
unsorted arrays.
Linear Search on an Unordered File
• Basic algorithm:
Get the search criterion (key)
Get the first record from the file
While ( (record != key) and (still more records) )
Get the next record
End_while
0 1 2 3 4 5 6 7 8
10 5 17 7 12 14 25 15 3
Return 6
The item is
found
Sequential Search – 6
Example 2
0 1 2 3 4 5 6 7 8
10 5 17 7 12 14 25 15 3
Return -1
The item is not
found
Sequential Search Algorithms – 7
Method 1
Values
FindMin Method
FindMax Method
• 32 = 25 and 512 = 29
• 8 < 11 < 16 23 < 11 < 24
• 128 < 250 < 256 27 < 250 < 28
A Very Fast Algorithm!
Note: There are no algorithms that run faster than ‘log n’ time.
Binary Search 17
Code
Time Complexity
Space Complexity
O(1)
O(1)