Day 10 - Sorting and Searching
Day 10 - Sorting and Searching
58
Linear Search vs. Binary Search 59
60
Next, let's take a quick look at some advanced search algorithms like
Ternary Search, Jump Search, Exponential Search, and Fibonacci
Search. These algorithms are highly efficient for searching through
sorted data. Given our limited time, we'll focus on providing a brief
overview of how each one works, rather than diving into complex
details such as time complexity, or data structures, etc. We'll cover
those more thoroughly in the advanced lessons.
61
❖ Sorting Algorithms
❑ Selection Sort
❑ Insertion Sort
❑ Bubble Sort
❑ Merge Sort
❑ Quick Sort
❖ Searching Algorithms
❑ Linear Search
❑ Binary Search
❑ Ternary Search
❑ Jump Search
❑ Exponential Search
❑ Fibonacci Search
❖ Final Touches
Searching Algorithms – Ternary Search 62
❖ Computer systems use different methods to find specific data. There are various search
algorithms, each better suited for certain situations. For instance, a binary search
divides information into two parts, while a ternary search does the same but into three
equal parts. It’s worth noting that ternary search is only effective for sorted data.
❖ Ternary search is a search algorithm that is used to find the position of a target value
within a sorted array. It operates on the principle of dividing the array into three parts
instead of two, as in binary search. The basic idea is to narrow down the search space
by comparing the target value with elements at two points that divide the array into
three equal parts:
❑ mid1 = left + (right - left) / 3
❑ mid2 = right – (right - left) / 3
Searching Algorithms – Ternary Search 63
❖ The Ternary Search can be represented as follows:
Searching Algorithms – Ternary Search 64
❖ Write a method to search an element in an array using the ternary search technique.
// Function to perform Ternary Search
public static int ternarySearch(int[] arr, int left, int right, int target) {
if (right >= left) {
int mid1 = left + (right - left) / 3;
int mid2 = right - (right - left) / 3;
// Check if target is at mid1
if (arr[mid1] == target) {
return mid1;
}
// Check if target is at mid2
if (arr[mid2] == target) {
return mid2;
}
// If target is in the left one-third
if (target < arr[mid1]) {
return ternarySearch(arr, left, mid1 - 1, target);
}
// If target is in the right one-third
if (target > arr[mid2]) {
return ternarySearch(arr, mid2 + 1, right, target);
}
// If target is in the middle one-third
return ternarySearch(arr, mid1 + 1, mid2 - 1, target);
}
// Target is not found
return -1;
}
Practice:
Ternary Search
66
❖ Sorting Algorithms
❑ Selection Sort
❑ Insertion Sort
❑ Bubble Sort
❑ Merge Sort
❑ Quick Sort
❖ Searching Algorithms
❑ Linear Search
❑ Binary Search
❑ Ternary Search
❑ Jump Search
❑ Exponential Search
❑ Fibonacci Search
❖ Final Touches
Searching Algorithms – Jump Search 67
❖ Like Binary Search, Jump Search is a searching algorithm for sorted arrays. The basic
idea is to check fewer elements (than linear search) by jumping ahead by fixed steps or
skipping some elements in place of searching all elements.
❖ For example, suppose we have an array arr[] of size n and a block (to be jumped) of
size m. Then we search in the indexes arr[0], arr[m], arr[2m]…..arr[km], and so on.
Once we find the interval (arr[km] < x < arr[(k+1)m]), we perform a linear search
operation from the index km to find the element x.
Searching Algorithms – Jump Search 68
❖ The Jump Search can be represented as follows:
Searching Algorithms – Jump Search 69
❖ Write a method to search an element in an array using the jump search technique.
// Method to perform Jump Search
public static int jumpSearch(int[] arr, int target) {
int n = arr.length;
// Finding the block size to be jumped
int step = (int) Math.floor(Math.sqrt(n));
// Finding the block where the element may be present
int prev = 0;
while (arr[Math.min(step, n) - 1] < target) {
prev = step;
step += (int) Math.floor(Math.sqrt(n));
if (prev >= n)
return -1; // Element is not present
}
// Doing a linear search for target in the block starting with prev
while (arr[prev] < target) {
prev++;
// If we reached the next block or end of array
if (prev == Math.min(step, n))
return -1; // Element is not present
}
// If element is found
if (arr[prev] == target)
return prev;
return -1; // Element is not present
}
Practice:
Jump Search
71
❖ Sorting Algorithms
❑ Selection Sort
❑ Insertion Sort
❑ Bubble Sort
❑ Merge Sort
❑ Quick Sort
❖ Searching Algorithms
❑ Linear Search
❑ Binary Search
❑ Ternary Search
❑ Jump Search
❑ Exponential Search
❑ Fibonacci Search
❖ Final Touches
Searching Algorithms – Exponential Search 72
❖ Exponential Search focuses on a specific range of an input array, assuming that the desired element is
within that range, and performs a binary search on the specific smaller range. This algorithm is also known
as Doubling Search or Finger Search.
❖ It works similarly to Jump Search in that it divides the sorted input into blocks and performs a search on
a smaller scale. However, the difference lies in how the blocks are divided and the type of search applied
on a smaller scale (Jump Search applies linear search, while Exponential Search applies binary search).
❖ Therefore, this algorithm “jumps” exponentially using powers of 2. Simply put, the search is conducted on
blocks divided by pow(2, k), where 𝑘 is a non-negative integer. When the element at position pow(2, n)
exceeds the key, a binary search is performed on the current block.
Searching Algorithms – Exponential Search 73
❖ The Exponential Search can be represented as follows:
Begin
m := pow(2, k) // m is the block size
start := 1
low := 0
high := size – 1 // size is the size of input
if array[0] == key
return 0
while array[m] <= key AND m < size do
start := start + 1
m := pow(2, start)
while low <= high do:
mid = low + (high - low) / 2
if array[mid] == x
return mid
if array[mid] < x
low = mid + 1
else
high = mid - 1
done
return invalid location
End
Searching Algorithms – Exponential Search 74
❖ Write a method to search an element in an array using the exponential search technique.
// Function to perform binary search within a given range
public static int binarySearch(int[] arr, int left, int right, int key) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key)
return mid;
if (arr[mid] < key)
left = mid + 1;
else
right = mid - 1;
}
return -1; // Key not found
}
// Function to perform exponential search
public static int exponentialSearch(int[] arr, int key) {
int n = arr.length;
// If the element is at the first position
if (arr[0] == key)
return 0;
// Find range for binary search by repeated doubling
int i = 1;
while (i < n && arr[i] <= key)
i = i * 2;
// Perform binary search within the found range
return binarySearch(arr, i / 2, Math.min(i, n - 1), key);
}
Practice:
Exponential Search
76
❖ Sorting Algorithms
❑ Selection Sort
❑ Insertion Sort
❑ Bubble Sort
❑ Merge Sort
❑ Quick Sort
❖ Searching Algorithms
❑ Linear Search
❑ Binary Search
❑ Ternary Search
❑ Jump Search
❑ Exponential Search
❑ Fibonacci Search
❖ Final Touches
Searching Algorithms – Fibonacci Search 77
❖ The Fibonacci Search is a technique for searching a sorted array using a divide-and-conquer algorithm
that compresses the possible positions with Fibonacci numbers. Compared to the Binary Search, where
the sorted array is divided into two equally sized arrays, one of which is searched further, the Fibonacci
Search divides the array into two parts whose size corresponds to successive Fibonacci numbers. On
average, this means that around 4% more comparisons have to be carried out. However, it has the
advantage that only addition and subtraction are required to calculate the indices of the called array
elements.
❖ In addition, the conventional Binary Search requires bit-shift, division or multiplication operations, which
were less common at the time of the introduction of the Fibonacci Search. The Fibonacci Search has an
average and worst-case complexity of O(log n). The Fibonacci sequence has the property that a number
is the sum of its two incestors. Therefore, the sequence can be generated by repeated addition. The binary
search works by dividing the search area into equal parts (1:1). The Fibonacci Search can divide the
search range into parts that approximate 1:1.618, using simpler operations.
Searching Algorithms – Fibonacci Search 78
❖ The Fibonacci Search can be represented as follows:
86
Final Touches 87
❖ The Fibonacci Search Algorithm makes use of the Fibonacci Series to diminish the range of an array on
which the searching is set to be performed. With every iteration, the search range decreases making it
easier to locate the element in the array. The detailed procedure of the searching is seen below:
❖ Step 1 − As the first step, find the immediate Fibonacci number that is greater than or equal to the size of the
input array. Then, also hold the two preceding numbers of the selected Fibonacci number, that is, we hold Fm,
Fm-1, Fm-2 numbers from the Fibonacci Series.
❖ Step 2 − Initialize the offset value as -1, as we are considering the entire array as the searching range in the
beginning.
❖ Step 3 − Until Fm-2 is greater than 0, we perform the following steps:
❑ Compare the key element to be found with the element at index [min(offset+Fm-2,n-1)]. If a match is found, return the
index.
❑ If the key element is found to be lesser value than this element, we reduce the range of the input from 0 to the index of
this element. The Fibonacci numbers are also updated with Fm = Fm-2.
❑ But if the key element is greater than the element at this index, we remove the elements before this element from the
search range. The Fibonacci numbers are updated as Fm = Fm-1. The offset value is set to the index of this element.
❖ Step 4 − As there are two 1s in the Fibonacci series, there arises a case where your two preceding numbers will
become 1. So if Fm-1 becomes 1, there is only one element left in the array to be searched. We compare the key
element with that element and return the 1st index. Otherwise, the algorithm returns an unsuccessful search.
88
Thanks!
Any questions?
For an in-depth understanding of Java, I highly recommend
referring to the textbooks. This slide provides a brief overview
and may not cover all the details you're eager to explore!