Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fatemeh-afshari/714b615a3087bf821e1d8eee3fb87800 to your computer and use it in GitHub Desktop.
Save fatemeh-afshari/714b615a3087bf821e1d8eee3fb87800 to your computer and use it in GitHub Desktop.
KotlinPlayground
fun main() {
val list = listOf<Int>(1, 2, 3, 2, 1)
println(
"the pivot index is: ${
searchIndex(
list,
0,
list.size - 1,
null,
{ mid -> mid == 0 || mid == list.size - 1 },
{ mid -> list[mid] > list[mid - 1] && list[mid] > list[mid + 1] },
{ mid -> list[mid] > list[mid - 1] && list[mid] < list[mid + 1] })
} "
)
val sortedList = listOf<Int>(1, 2, 3, 4,5,7,8,9)
val target =8
println(
"the index of $target is: ${
searchIndex(
sortedList,
0,
sortedList.size - 1,
target,
{ _ ->false },
{ mid -> sortedList[mid]== target },
{ mid -> target> sortedList[mid] })
} "
)
}
fun searchIndex(
list: List<Int>,
startingIndex: Int,
endingIndex: Int,
target: Int? = null,
firstCondition: (mid: Int) -> Boolean,
secondCondition: (mid: Int) -> Boolean,
thirdCondition: (mid: Int) -> Boolean,
): Int {
val mid = (startingIndex + endingIndex) / 2
if (startingIndex > endingIndex) {
return -1
}
return when {
firstCondition(mid) -> -1
secondCondition(mid) -> mid
thirdCondition(mid) -> searchIndex(
list,
mid + 1,
endingIndex,
target,
firstCondition,
secondCondition,
thirdCondition
)
else -> searchIndex(
list, startingIndex,
mid - 1,
target,
firstCondition,
secondCondition,
thirdCondition
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment