Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
jump_search.c File Reference

Implementation of jump search algorithm. More...

#include <assert.h>
#include <math.h>
#include <stdio.h>
Include dependency graph for jump_search.c:

Macros

#define min(X, Y)   ((X) < (Y) ? (X) : (Y))
 Macro to return the minimum of two values.
 

Functions

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.
 

Detailed Description

Implementation of jump search algorithm.

Function Documentation

◆ jump_search()

int jump_search ( const int *  arr,
int  x,
size_t  n 
)

Implement Jump-search algorithm.

Parameters
[in]arrArray to search within
xvalue to search for
nlength 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()

int main ( void  )

Main function.

82{
83 test();
84 return 0;
85}
void test()
Test implementation of the function.
Definition: jump_search.c:58
Here is the call graph for this function:

◆ test()

void test ( void  )

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.... ");
65 int index = jump_search(arr, x, n);
66 assert(index == 10);
67 printf("passed\nTest 2.... ");
68 x = 56;
69 index = jump_search(arr, x, n);
70 assert(index == -1);
71 printf("passed\nTest 3.... ");
72 x = 13;
73 index = jump_search(arr, x, n);
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
Here is the call graph for this function: