Learn-dsa..in 30 days!



























CC-7 : Implement Jump Search Algorithm.

Description:

The Jump search algorithm works on sorted lists. The algorithm “jumps” or partitions the list by fixed index count steps, and performs linear search within this smaller jumped partition. Given an input array and an element to be searched, search the required element in the input array using Jump search.

Test cases and expected outputs:

Input Parameters Expected outputs
Array:
3, 22, 44, 67, 77, 96, 122, 144, 201,
122 found at index 6
76 found at index -1
3 found at index 0
201 found at index 8

Pseudocode:

jumpSearch(nums[], toSearch):

Integer array named nums, and integer named toSearch to be searched are received as input parameters.
Set integer variable jump to squareroot of nums.length. We will use variable jump to create partitions with index count same as value of jump.
Set integer prevIdx to zero, we will use this variable to check the first index of partition in which are searching for required integer.
Set integer variable currIdx to jump, we will use this variable to check the last index of partition in which are searching for required integer.
While (currIdx < nums.length) and nums[firstIdx] <= toSearch do the following steps:
Set prevIdx=currIdx.
Set currIdx=currIdx+Jump.
If (currIdx > nums.length):
Set currIdx=nums.length.
Iterate through using for loop with idx as iteration variable and values of idx ranging from prevIdx to currIdx-1:
If nums[idx]==toSearch, return idx, as we have found the index of the number that we were searching for.
If toSearch is not found in code above return -1, as the required element does not exist within the input array.

Code:

public int jumpSearch(int[] nums, int toSearch){
	int jump=(int)Math.sqrt(nums.length);
	int prevIdx=0;
	int currIdx=jump;
	while ((currIdx < nums.length)&&(nums[currIdx]<= toSearch)) {
		prevIdx=currIdx;
		currIdx=currIdx+jump;
	}
	if (currIdx > nums.length) {
		currIdx=nums.length;
	}
	for (int idx=prevIdx; idx < currIdx; idx++){
		if (nums[idx]==toSearch) {
			return idx;
		}
	}
	return -1;
}

Click here to download and run code and test cases !