From ec35fca77d6e0d8e90c20a18a6013240742b0738 Mon Sep 17 00:00:00 2001 From: Amisha Mohapatra Date: Fri, 22 Jan 2021 22:20:07 +0530 Subject: [PATCH] Add jump search java program (#24) * Add binary search javascript program * Add jump-search-java program * Delete stdout.txt --- searching/README.md | 1 + searching/java/jump-search.java | 55 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 searching/java/jump-search.java diff --git a/searching/README.md b/searching/README.md index db735be1..0f682034 100644 --- a/searching/README.md +++ b/searching/README.md @@ -19,5 +19,6 @@ 1. [Linear Search](java/linear-search.java) 2. [Binary Search](java/binary-search.java) +3. [Jump Search](java/jump-search.java) diff --git a/searching/java/jump-search.java b/searching/java/jump-search.java new file mode 100644 index 00000000..d90cdd6b --- /dev/null +++ b/searching/java/jump-search.java @@ -0,0 +1,55 @@ +// Java program to implement Jump Search. +public class JumpSearch +{ + public static int jumpSearch(int[] arr, int x) + { + int n = arr.length; + + // Finding block size to be jumped + int step = (int)Math.floor(Math.sqrt(n)); + + // Finding the block where element is + // present (if it is present) + 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; + } + + // Doing a linear search for x in block + // beginning with prev. + 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; + } + + // Driver program to test 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; + + // Find the index of 'x' using Jump Search + int index = jumpSearch(arr, x); + + // Print the index where 'x' is located + System.out.println("\nNumber " + x + + " is at index " + index); + } +} \ No newline at end of file