FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/src/main/java/com/search/ExponentialSearch.java at Development · iDev-git/Java · GitHub
iDev-git
Java
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
search
/
ExponentialSearch.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
41 lines (36 loc) · 1.35 KB
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
search
/
ExponentialSearch.java
Copy path
File metadata and controls
41 lines (36 loc) · 1.35 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
com
.
search
;
import
java
.
util
.
Arrays
;
/**
* Exponential search (also called doubling search or galloping search or Struzik search) is an algorithm which finds
* the position of a target value within an array. It works by determining a range that the search key resides in and
* performing a binary search within that range
* <p>
* Worst-case performance O(n)
* Best-case performance O(1)
* Average performance O(Log n)
* Worst-case space complexity O(Log n)
*/
public
class
ExponentialSearch
{
/**
* @param array is an array where the element should be found
* @param key is an element which should be found
* @param <T> is any comparable type
* @return The index position of the key in the array, returns -1 for empty array
*/
public
<
T
extends
Comparable
<
T
>>
int
findIndex
(
T
[]
array
,
T
key
) {
if
(
array
==
null
||
array
.
length
==
0
) {
return
-
1
;
}
int
size
=
array
.
length
;
// If the element is present at first position
if
(
array
[
0
] ==
key
)
return
0
;
// Find the range for binary search by repeated doubling
int
i
=
1
;
while
(
i
<
size
&&
array
[
i
].
compareTo
(
key
) <=
0
) {
i
<<=
1
;
}
// Call binary search for the range found
return
Arrays
.
binarySearch
(
array
,
i
>>
1
,
Math
.
min
(
i
,
size
),
key
);
}
}
Back
|
FazBrowse Home
|
New Git URL