You are on page 1of 15

Linear search and binary search

Sequential Search(Linear search) O (n)


A sequential search of a list/array begins at the beginning of the list/array and continues until the item is found or the entire list/array has been searched

Data Structures Using C++

Search Algorithms
Suppose that there are n elements in the array. The following expression gives the average number of comparisons:

It is known that

Therefore, the following expression gives the average number of comparisons made by the sequential search in the successful case:

Data Structures Using C++

Algorithm for Linear Search


1) set loc=1 [initialize counter] [now search the item] 2)Repeat if DATA[LOC]!=Item: Set Loc=loc+1; Else Print :data found 3) Exit loop [end of loop] 4)Exit program

Search Algorithms

Data Structures Using C++

Binary Search O(log2 n)

A binary search looks for an item in a list using a divide-andconquer strategy

Data Structures Using C++

Binary Search
Binary search algorithm assumes that the items in the array being searched are sorted

The algorithm begins at the middle of the array in a binary search


If the item for which we are searching is less than the item in the middle, we know that the item wont be in the second half of the array Once again we examine the middle element The process continues with each comparison cutting in half the portion of the array where the item might be
Data Structures Using C++ 7

Binary Search

Data Structures Using C++

Binary Search: middle element

mid =

left + right 2

Data Structures Using C++

Binary Search: Example

Data Structures Using C++

11

Binary Search

Data Structures Using C++

12

Binary Search

Data Structures Using C++

13

Efficiency of Binary Search


The binary search algorithm is extremely fast compared to an algorithm that tries all array elements in order
About half the array is eliminated from consideration right at the start Then a quarter of the array, then an eighth of the array, and so forth

14

2006 Pearson Addison-Wesley. All rights reserved

Efficiency of Binary Search


Given an array with 1,000 elements, the binary search will only need to compare about 10 array elements to the key value, as compared to an average of 500 for a serial search algorithm The binary search algorithm has a worst-case running time that is logarithmic: O(log n)
A serial search algorithm is linear: O(n)

If desired, the recursive version of the method search can be converted to an iterative version that will run more efficiently

15

2006 Pearson Addison-Wesley. All rights reserved

You might also like