Created
March 7, 2023 14:08
-
-
Save fatemeh-afshari/714b615a3087bf821e1d8eee3fb87800 to your computer and use it in GitHub Desktop.
KotlinPlayground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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