Created
April 28, 2017 18:54
-
-
Save mateusmarquezini/2a8bfa11caaa75c305a92e4b6694dc1e to your computer and use it in GitHub Desktop.
Binary Search in Kotlin
This file contains hidden or 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
package binarySearch | |
import java.util.* | |
/** | |
* Created by Mateus Marquezini on 28/04/2017. | |
*/ | |
class BinarySearch | |
fun main(args: Array<String>){ | |
print(binarySearch(23, arrayOf(12, 3, 24, 5, 10, 23, 9))) | |
} | |
fun binarySearch(element: Int, array: Array<Int>): Int { | |
Arrays.sort(array) | |
var index: Int = 0 | |
var end = array.size - 1 | |
while(index <= end){ | |
val center: Int = (index + end) / 2 | |
if (element == array[center]){ | |
return center | |
}else if (element < array[center]){ | |
end = center - 1 | |
}else if(element > array[center]){ | |
index = center + 1 | |
} | |
} | |
return -1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment