Lecture 10
Lecture 10
2
Sequential search
3
Searching
4
Successful
search of an
unordered list
5
Unsuccessful
search in
unordered list
6
Sequential Search
int LinSearch(int x[ ], int n, int item){
for(int i=0;i<n;i++){
if(x[i]==item) return i;
else return -1;
}
}
Search Algorithms
8
Binary Search O(log2 n)
9
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 won’t 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
10
Binary Search Algorithm (Cont’d)
• Determine whether 75 is in the list
left + right
mid =
2
13
Binary
search
example
begin end
mid
2
first last
mid
2
14
Unsuccessful
binary
search
example
15
Binary Search
boolean BinSearch(int list[ ], int n, int item, int index){
int left=0; int right=n-1; int mid;
while(left<=right){
mid=(left+right)/2;
if(item> list [mid])
{ left=mid+1; }
else if(item< list [mid])
{right=mid-1;}
else{
Item= list [mid];
index=mid;
return true;
}
}// while
return false; }
16
Binary Search
17