forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjumpserach.c
More file actions
51 lines (40 loc) · 1.15 KB
/
Copy pathjumpserach.c
File metadata and controls
51 lines (40 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <math.h>
// Function to perform jump search
int jumpSearch(int arr[], int n, int target) {
int step = sqrt(n); // jump size
int prev = 0;
// Jump ahead until we find a block containing the target
while (arr[(step < n ? step : n) - 1] < target) {
prev = step;
step += sqrt(n);
if (prev >= n) {
return -1; // target not found
}
}
// Linear search within the block
for (int i = prev; i < (step < n ? step : n); i++) {
if (arr[i] == target) {
return i; // target found, return index
}
}
return -1; // target not found
}
int main() {
int n, target;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d sorted elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter element to search: ");
scanf("%d", &target);
int index = jumpSearch(arr, n, target);
if (index != -1)
printf("Element %d found at index %d.\n", target, index);
else
printf("Element %d not found in the array.\n", target);
return 0;
}