Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 3b1f6cb

Browse filesBrowse files
author
night
committed
binary searych IndexEqualsValue
1 parent cdef253 commit 3b1f6cb
Copy full SHA for 3b1f6cb

File tree

Expand file treeCollapse file tree

1 file changed

+25
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+25
-0
lines changed
+25Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.blankj.pramp
2+
3+
import com.blankj.ext.print
4+
5+
class IndexEqualsValueSearch {
6+
7+
fun indexEqualsValueSearch(arr: IntArray): Int {
8+
var low = 0
9+
var high = arr.lastIndex
10+
while (low <= high) {
11+
val mid = low + ((high - low) shr 1)
12+
when {
13+
arr[mid] == mid && (mid == 0 || arr[mid - 1] < mid - 1) -> return mid
14+
arr[mid] < mid -> low = mid + 1
15+
else -> high = mid - 1
16+
}
17+
}
18+
return -1
19+
}
20+
}
21+
22+
fun main() {
23+
IndexEqualsValueSearch().indexEqualsValueSearch(intArrayOf(-8, 0, 2, 5)).print()
24+
IndexEqualsValueSearch().indexEqualsValueSearch(intArrayOf(1, 0, 3, 6)).print()
25+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.