Implementation of jump search algorithm.
More...
#include <assert.h>
#include <math.h>
#include <stdio.h>
|
#define | min(X, Y) ((X) < (Y) ? (X) : (Y)) |
| Macro to return the minimum of two values.
|
|
|
int | jump_search (const int *arr, int x, size_t n) |
| Implement Jump-search algorithm.
|
|
void | test () |
| Test implementation of the function.
|
|
int | main () |
| Main function.
|
|
Implementation of jump search algorithm.
◆ jump_search()
int jump_search |
( |
const int * |
arr, |
|
|
int |
x, |
|
|
size_t |
n |
|
) |
| |
Implement Jump-search algorithm.
- Parameters
-
[in] | arr | Array to search within |
| x | value to search for |
| n | length of array |
- Returns
- index where the value was found
-
-1 if value not found
25{
26 int step = floor(sqrt(n));
27 int prev = 0;
28
29 while (arr[
min(step, n) - 1] < x)
30 {
31 prev = step;
32 step += floor(sqrt(n));
33 if (prev >= n)
34 {
35 return -1;
36 }
37 }
38
39 while (arr[prev] < x)
40 {
41 prev = prev + 1;
42 if (prev ==
min(step, n))
43 {
44 return -1;
45 }
46 }
47 if (arr[prev] == x)
48 {
49 return prev;
50 }
51 return -1;
52}
#define min(X, Y)
Macro to return the minimum of two values.
Definition: jump_search.c:13
◆ main()
Main function.
82{
84 return 0;
85}
void test()
Test implementation of the function.
Definition: jump_search.c:58
◆ test()
Test implementation of the function.
59{
60 int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610};
61 size_t n = sizeof(arr) / sizeof(int);
62
63 int x = 55;
64 printf("Test 1.... ");
66 assert(index == 10);
67 printf("passed\nTest 2.... ");
68 x = 56;
70 assert(index == -1);
71 printf("passed\nTest 3.... ");
72 x = 13;
74 assert(index == 7);
75 printf("passed\n");
76}
int jump_search(const int *arr, int x, size_t n)
Implement Jump-search algorithm.
Definition: jump_search.c:24