- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathJumpSearcher.cs
61 lines (53 loc) · 1.87 KB
/
JumpSearcher.cs
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
52
53
54
55
56
57
58
59
60
61
usingSystem;
namespaceAlgorithms.Search;
/// <summary>
/// Jump Search checks fewer elements by jumping ahead by fixed steps.
/// The optimal steps to jump is √n, where n refers to the number of elements in the array.
/// Time Complexity: O(√n)
/// Note: The array has to be sorted beforehand.
/// </summary>
/// <typeparam name="T">Type of the array element.</typeparam>
publicclassJumpSearcher<T>whereT:IComparable<T>
{
/// <summary>
/// Find the index of the item searched for in the array.
/// </summary>
/// <param name="sortedArray">Sorted array to be search in. Cannot be null.</param>
/// <param name="searchItem">Item to be search for. Cannot be null.</param>
/// <returns>If item is found, return index. If array is empty or item not found, return -1.</returns>
publicintFindIndex(T[]sortedArray,TsearchItem)
{
if(sortedArrayisnull)
{
thrownewArgumentNullException("sortedArray");
}
if(searchItemisnull)
{
thrownewArgumentNullException("searchItem");
}
intjumpStep=(int)Math.Floor(Math.Sqrt(sortedArray.Length));
intcurrentIndex=0;
intnextIndex=jumpStep;
if(sortedArray.Length!=0)
{
while(sortedArray[nextIndex-1].CompareTo(searchItem)<0)
{
currentIndex=nextIndex;
nextIndex+=jumpStep;
if(nextIndex>=sortedArray.Length)
{
nextIndex=sortedArray.Length-1;
break;
}
}
for(inti=currentIndex;i<=nextIndex;i++)
{
if(sortedArray[i].CompareTo(searchItem)==0)
{
returni;
}
}
}
return-1;
}
}