From 4025ad7de4199cc080abc4a4e8ea0e1a05f04c31 Mon Sep 17 00:00:00 2001 From: priyankaanandd Date: Fri, 31 Oct 2025 16:44:44 +0530 Subject: [PATCH] feat: Add Jump Search algorithm in C++ --- Jump_Search_Algo/JumpSearch.cpp | 73 +++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Jump_Search_Algo/JumpSearch.cpp diff --git a/Jump_Search_Algo/JumpSearch.cpp b/Jump_Search_Algo/JumpSearch.cpp new file mode 100644 index 0000000..4f27d65 --- /dev/null +++ b/Jump_Search_Algo/JumpSearch.cpp @@ -0,0 +1,73 @@ +/* +* C++ program to implement Jump 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. +*/ + +#include +#include +#include +#include + +int jumpSearch(const std::vector& arr, int x) { + int n = arr.size(); + + // Finding block size to be jumped + int step = std::sqrt(n); + + // Finding the block where element is + // present (if it is present) + int prev = 0; + while (arr[std::min(step, n) - 1] < x) { + prev = step; + step += std::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 == std::min(step, n)) + return -1; + } + + // If element is found + if (arr[prev] == x) + return prev; + + return -1; +} + +// Main function to test the algorithm +int main() { + std::vector 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); + + if (index != -1) { + std::cout << "Number " << x << " is at index " << index << std::endl; + } else { + std::cout << "Number " << x << " is not in the array" << std::endl; + } + + x = 7; + index = jumpSearch(arr, x); + + if (index != -1) { + std::cout << "Number " << x << " is at index " << index << std::endl; + } else { + std::cout << "Number " << x << " is not in the array" << std::endl; + } + + return 0; +} \ No newline at end of file