Objectives To implement interesting search algorithms To interpret specification
ID: 3865602 • Letter: O
Question
Objectives To implement interesting search algorithms To interpret specifications, and mathematical models To design an algorithm To implement the designed algorithm Instructions When an object does not occur in an array, a sequential search for it must examine the entire array. A ump search is an attempt to reduce the number of comparisons with the traditional sequential search. Instead of examining the n objects in the array a sequentially, you look at the elements a[j], a[2j], a[3j], and so on, for some positive jExplanation / Answer
Just like Binary Search, Jump Search is a searching algorithm for sorted arrays. The idea is to check fewer elements by jumping ahead by fixed steps or skipping some elements in place of searching all elements.
Let us consider the following array: (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610). Length of the array is 16. Jump search will find the value of 55 with the following steps assuming that the block size to be jumped is 4.
STEP 1: Jump from index 0 to index 4;
STEP 2: Jump from index 4 to index 8;
STEP 3: Jump from index 8 to index 16;
STEP 4: Since the element at index 16 is greater than 55 we will jump back a step to come to index 9.
STEP 5: Perform linear search from index 9 to get the element 55.
In the worst case, we have to do n/m jumps and if the last checked value is greater than the element to be searched for, we perform m-1 comparisons more for linear search. Therefore the total number of comparisons in the worst case will be ((n/m) + m-1). The value of the function ((n/m) + m-1) will be minimum when m = n. Therefore, the best step size is m = n.
Java Code:
public class JumpSearch
{
public static int jumpSearch(int[] arr, int x)
{
int n = arr.length;
int step = (int)Math.floor(Math.sqrt(n));
int prev = 0;
while (arr[Math.min(step, n)-1] < x)
{
prev = step;
step += (int)Math.floor(Math.sqrt(n));
if (prev >= n)
return -1;
}
while (arr[prev] < x)
{
prev++;
// If we reached next block or end of array, element is not present.
if (prev == Math.min(step, n)) return -1;
}
// If element is found
if (arr[prev] == x) return prev;
return -1;
}
// Main Function
public static void main(String [ ] args)
{
int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,34, 55, 89, 144, 233, 377, 610};
int x = 55;
int index = jumpSearch(arr, x);
System.out.println(" Number " + x +" is at index " + index);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.