Lec7 Algorithm Design 24-25 Course2 Stage2
Lec7 Algorithm Design 24-25 Course2 Stage2
Nadia Fadhil
Searching methods
Searching operation is the process of finding an item in the array that meets some specified
criterion.Some common searching methods:
1. Linear Search (Sequential Search) (in an unordered array).
2. Binary Search.
1. Linear Search
Look at each item in the array in turn, and check whether that item is the one you are looking
for.
If so, the search is finished and the method returns its index.
If it is not found, then the method returns -1.
This method is benefit if nothing is known about the order of the items in the array.
2. Binary Search
Is a method for searching for a given item in a sorted array.
0 4 LO
1 7
2 16
3 20 MID
4 37
5 38
6 43 HI
Variables LO and HI keep track of the lower bound and upper bound of the array,
respectively.
Begin searching by examining the middle element of the array.
If the key we are searching for is equal to the middle element then returns MID, else if it is
less than the middle element, then set HI to (MID – 1). Else set LO to (MID + 1).
In this way, each iteration halves the size of the array to be searched.
42
Lecture 7 Algorithm Design and Analysis 2024-2025 Ass.Prof.Dr. Nadia Fadhil
public static int binary(int key, int[] a, int lo, int hi)
{
if (lo > hi) return -1;
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) return binary (key, a, lo, mid - 1);
else if (key > a[mid]) return binary (key, a, mid + 1, hi);
else
return mid;
}
LO=0 HI=12
MID=LO+ (HI-LO)/2=0+ (12-0)/2=6
0 1 2 3 4 5 6 7 8 9 10 11 12
4 16 22 23 37 54 65 67 68 73 82 87 89
Lo M ID HI
LO=MID+1=6+1=7 HI=12
MID=LO+ (HI-LO)/2=7+ (12-7)/2=9
0 1 2 3 4 5 6 7 8 9 10 11 12
4 16 22 23 37 54 65 67 68 73 82 87 89
LO MID HI
LO=MID+1=9+1=10 HI=12
MID=LO+ (HI-LO)/2=10+ (12-10)/2=11
0 1 2 3 4 5 6 7 8 9 10 11 12
4 16 22 23 37 54 65 67 68 73 82 87 89
LO MID HI
This is a powerful method. Given an array of 1023 elements, we can narrow the search to
511 elements in one comparison. After another comparison, and we’re looking at only 255
elements. In fact, we can search the entire array in only 10 comparisons.
43
Lecture 7 Algorithm Design and Analysis 2024-2025 Ass.Prof.Dr. Nadia Fadhil
44