Lecture 1.2.3
Lecture 1.2.3
Lecture 1.2.3
ENGINEERING
DEPARTMENT OF COMPUTER
SCIENCE AND ENGG.
Bachelor of Engineering (Computer Science & Engineering)
DATA STRUCTURES 21CSH-211
• Searching
• Linear Search
• Binary Search
2
Searching
3
Search Element using Linear Search
4
Linear Search
LINEAR(DATA, N, ITEM, LOC)
Here DATA is a linear array with N elements, and ITEM is a given item of information.
This algorithm finds the location LOC of ITEM in DATA, or sets LOC = 0 if the search
is unsuccessful.
1. [Insert ITEM at the end of DATA] Set DATA[N+1] = ITEM
2. [Initialize counter] Set LOC = 1
3. [Search for ITEM]
Repeat while DATA[LOC] ≠ ITEM
Set LOC = LOC + 1
[End of loop]
4. [Successful?] If LOC = N+1, then: Set Loc = 0
5. Exit
5
Algorithm
7
Binary Search
8
Binary Search Algorithm
• Binary search algorithm is efficient if the array is sorted.
• A binary search is used whenever the list starts to become large.
• Consider to use binary searches whenever the list contains more than 16
elements.
• The binary search starts by testing the data in the element at the middle of
the array to determine if the target is in the first or second half of the list.
• If it is in the first half, we do not need to check the second half. If it is in
the second half, we do not need to test the first half. In other words we
eliminate half the list from further consideration. We repeat this process
until we find the target or determine that it is not in the list.
9
Example
10
Binary Search Algorithm
1. [Define variables]
ST = LB, LAST= UB;
MID = (ST+LAST)/2;
Repeat 3 and 4 DO ST <= LAST & DATA[MID] != ITEM
3. If ITEM < DATA[MID] then
LAST = MID-1
If not
ST = MID+1
4. Set MID = INT((ST + LAST)/2)
[LAST repeat to 2]
5. If DATA[MID] = ITEM then
LOK = MID
If not,
LOK = NULL
6. Stop
11
References
• Lipschutz, Seymour, “Data Structures”, Schaum's Outline Series, Tata McGraw Hill.
• Goodrich, Michael T., Tamassia, Roberto, and Mount, David M., “Data Structures and Algorithms in C++”, Wiley
Student Edition.
• https://www.tutorialspoint.com/data_structures_algorithms/algorithms_basics.htm
• https://www.cs.utexas.edu/users/djimenez/utsa/cs1723/lecturehtml
• https://www.w3resource.com/php-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-4.
php
• https://www.programiz.com/dsa/merge-sort
• https://www.geeksforgeeks.org/binary-search/
12
THANK YOU