-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJump.cs
More file actions
38 lines (29 loc) · 1.12 KB
/
Jump.cs
File metadata and controls
38 lines (29 loc) · 1.12 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
using System;
namespace AlgorithmsAndDataStructures.Algorithms.Search;
public class Jump<T> : ISearchAlgorithm<T> where T : IComparable<T>
{
public int Search(T[] target, T value)
{
if (target is null) return default;
var jumpStep = (int)Math.Sqrt(target.Length);
var currentJump = jumpStep;
while (currentJump < target.Length)
{
if (target[currentJump].CompareTo(value) == 0) return currentJump;
if (target[currentJump].CompareTo(value) > 0)
{
// Search latest jumped interval with simple linear search.
for (var i = currentJump - jumpStep; i < currentJump; i++)
if (target[i].CompareTo(value) == 0)
return i;
return -1;
}
currentJump += jumpStep;
}
// Search latest jumped interval with simple linear search.
for (var i = currentJump - jumpStep; i < target.Length; i++)
if (target[i].CompareTo(value) == 0)
return i;
return -1;
}
}