0% found this document useful (0 votes)
10 views26 pages

CMP 202 (Searching)

Uploaded by

Akorede Bashir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views26 pages

CMP 202 (Searching)

Uploaded by

Akorede Bashir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Usmanu Danfodiyo University, Sokoto

Department of Computer Science

CMP 202: Computer Programming II

SEARCHING

1
CONTENTS

✓ What is Searching?

✓ Types of Searching

▪ Linear Search

▪ Binary Search

2
WHAT IS SEARCHING?

3
SEARCHING
❖ We know that today’s computers store a lot of information.
❖ To retrieve this information proficiently we need a very efficient way of
doing it and to make sure we are retrieving the right information.

❖ Searching is a method or procedure used to find a specific item or element


within a collection of data.
❖ These methods/procedures are widely used in computer science and are
crucial for tasks like:
✓ Searching for a particular record in a database,
✓ finding an element in a sorted list, or
✓ locating a file on a computer. 4
SEARCHING (Cont)…
❖ Searching is one of the most common actions performed in regular business
applications.
❖ This involves fetching data stored in structures like Arrays, List, Map, etc.
❖ More often than not, this search operation determines the responsiveness
of the application for the end-user.
❖ There are certain ways of organizing the data that improve the search
process.
❖ That means, if we keep the data in proper order, it is easy to search for the
required element.
❖ Sorting is one of the techniques for making the elements ordered
5
TYPES OF SEARCHING
❖ Here are some common types of search algorithms.
✓ Linear Search
✓ Binary Search
✓ Hashing
✓ Interpolation Search
✓ Tree-based Searching
✓ Ternary Search
✓ Jump Search
✓ Exponential Search
✓ Fibonacci Search
✓ Interpolation Search for Trees
✓ Hash-based Searching (e.g., Bloom Filter)
✓ String Searching Algorithms
6
LINEAR SEARCH

7
LINEAR SEARCH
✓ Linear or Sequential Search is the simplest of search algorithms.

✓ Linear Search has no pre-requisites for the state of the underlying data

structure.

✓ Linear Search involves sequential searching for an element in the given

data structure until either the element is found or the end of the structure is

reached.

✓ If the element is found, we usually just return its position in the data

structure.

✓ If not, we usually return -1


8
LINEAR SEARCH (CONT)...
✓ Let the element to be searched be x.
✓ Start from the leftmost element of arr[ ] and one by one compare x with
each element of arr[ ].
✓ If x matches with an element then return that index.
✓ If x doesn’t match with any of the elements then return -1.

9
LINEAR SEARCH (Example)
public static int linearSearch(int arr[], int elementToSearch) {

for (int index = 0; index < arr.length; index++) {

if (arr[index] == elementToSearch)

return index;

return -1;

}
10
LINEAR SEARCH (Example)...
To test it, we'll use a simple Array of integers: Here, we are searching for “67” in the below array

89 57 91 47 95 3 27 22 67 99

With a simple helper method to print the result:


public static void print(int elementToSearch, int index) {
if (index == -1){
System.out.println(elementToSearch + " not found.");
}
else {
System.out.println(elementToSearch + " found at index: " + index);
}
}
Output ➔ 67 found at index: 8
11
LINEAR SEARCH (Examples)…..
class linearSearch {
// Function for linear search
public static int search(int arr[ ], int x)
{
int n = arr.length;
// Traverse array arr[]
for (int i = 0; i < n; i++) {
// If element found then return that index
if (arr[i] == x)
return i;
}
return -1;
}
12
LINEAR SEARCH (Example)...
// Driver Code
public static void main(String args[])
{ 2 3 4 10 40
// Given arr[]
int arr[] = { 2, 3, 4, 10, 40 };
// Element to search
int x = 10;
// Function Call Output:
int result = search(arr, x);
Element is present at index 3
if (result == -1)
System.out.print("Element is not present in
array");
else
System.out.print("Element is present" + " at index
" + result);
}
} 13
APPLICATIONS OF LINEAR SEARCH
Linear search has several practical applications in computer science and beyond. Here are
some examples:

✓ Phonebook Search: Linear search can be used to search through a phonebook to find a
person’s name, given their phone number.
✓ Spell Checkers: The algorithm compares each word in the document to a dictionary of
correctly spelled words until a match is found.
✓ Finding Minimum and Maximum Values: Linear search can be used to find the minimum
and maximum values in an array or list.
✓ Searching through unsorted data: Linear search is useful for searching through unsorted
data.

14
ADVANTAGES OF LINEAR SEARCH
✓ Simplicity: Linear search is a very simple algorithm to understand and
implement.
✓ Works with unsorted data: Linear search works well with unsorted data. It
does not require any pre-processing or sorting of the data before
performing the search.
✓ Low memory usage: Linear search only requires a small amount of memory
to store the index of the current element being searched.
✓ Easy to debug: Because linear search is a simple algorithm, it is easy to
debug and troubleshoot any issues that may arise.
15
DISADVANTAGES OF LINEAR SEARCH
✓ Inefficient for large datasets: As the size of the dataset grows, the time
taken by linear search also increases proportionally.
✓ Limited applicability: Linear search is only suitable for datasets that are not
too large or not too complex.
✓ No early termination: Linear search does not have a mechanism to
terminate early once the target element is found.
✓ Inefficient for sorted data: When the data is already sorted, linear search is
not efficient because it needs to check each element one by one, even if
it has already passed the target element.
16
BINARY SEARCH

17
BINARY SEARCH
❖ Binary or Logarithmic Search is one of the most commonly used search
algorithms primarily due to its quick search time.

❖ This kind of search uses the Divide and Conquer methodology and requires
the data set to be sorted beforehand.
❖ If data is not sorted, then it to be sorted or we use Linear Search

❖ It divides the input collection into equal halves, and with each iteration
compares the target element with the element in the middle.

18
BINARY SEARCH (CONT)....
❖ If the element is found, the search ends.

❖ Else, we continue looking for the element by dividing and selecting the
appropriate partition of the array, based on if the target element is
smaller or bigger than the middle element.

❖ The search terminates when the firstIndex (our pointer) goes


past lastIndex (last element), which implies we have searched the whole
array and the element is not present.

19
BINARY SEARCH (CONT)....
Below are the steps:

✓ Compare x with the middle element.

✓ If x matches with middle element, we return the mid index.

✓ Else If x is greater than the mid element, then x can only lie in the right half
subarray after the mid element. So we recur for right half.

✓ Else (x is smaller) recur for the left half.

20
BINARY SEARCH (Example)...
Let’s use the below array

3 11 21 29 41 54 61 78 110 127

✓ Target element is 78.

✓ Divide the array index into 2 equal halves (9/2) = 4.5 = 4

✓ Element @ index 4 is not equal to 78 but it is less than 78

✓ Therefore we element the first half of the array:

54 61 78 110 127

✓ Divide the array into 2 equal halves (4/2) = 2

✓ Element @ index 2 is equal to 78

21
BINARY SEARCH (Example)...
public static int binarySearch(int arr[], int firstElement, int lastElement,
int elementToSearch) {

// termination condition

if (lastElement >= firstElement) {

int mid = firstElement + (lastElement - firstElement) / 2;

// if the middle element is our goal element, return its index

if (arr[mid] == elementToSearch)

return mid;

3 22 27 47 57 67 89 91 95 99
22
BINARY SEARCH (Example)...
// if the middle element is bigger than the goal element

if (arr[mid] > elementToSearch)

return binarySearch(arr, firstElement, mid - 1, elementToSearch);

// else, recursively call the method with narrowed data

return binarySearch(arr, mid + 1, lastElement, elementToSearch);

return -1;
Output:
} 67 found at index: 5
We can use this algorithm like this:

int index = binarySearch(new int[]{3, 22, 27, 47, 57, 67, 89, 91, 95, 99}
23
ADVANTAGES OF BINARY SEARCH

✓ Since it follows the technique to eliminate half of the array elements, it is


more efficient as compared to linear search for large data.

✓ Better time complexity and thus takes less compilation time.

✓ An improvement over linear search as it breaks the array down in half


rather than sequentially traversing through the array elements.

24
DISADVANTAGES OF BINARY SEARCH

✓ Binary Search algorithm could only be implemented over a sorted array.

✓ Small unsorted arrays would take considerate time in sorting and then
searching the desired element.

✓ So, binary search is not preferred in such cases.

✓ It has poor locality of reference compared to linear search algorithm


when comes to in-memory searching for short intervals.

25
APPLICATIONS OF BINARY SEARCH
❖ It is the most commonly used search algorithm in most of the libraries for searching.

❖ The Binary Search tree is used by many data structures as well which store sorted data.

26

You might also like