In this article, we will learn to write a kotlin program to sort an array and to search element inside it. To accomplish this task, we will use binarySearch() and sort() methods.
Source Code:
import java.util.Arrays
private fun printArray(message: String, array: IntArray) {
print(message)
for (i in array.indices) {
if (i != 0) {
print(", ")
}
print(array[i])
}
println()
}
fun main(args: Array<String>) {
val array = intArrayOf(2, 5, -2, 1, -3, 3, -1, -5, -4, 4)
Arrays.sort(array)
printArray("Sorted array is : ", array)
val index = Arrays.binarySearch(array, 2)
println("Element 2 found @ $index")
}
Output:private fun printArray(message: String, array: IntArray) {
print(message)
for (i in array.indices) {
if (i != 0) {
print(", ")
}
print(array[i])
}
println()
}
fun main(args: Array<String>) {
val array = intArrayOf(2, 5, -2, 1, -3, 3, -1, -5, -4, 4)
Arrays.sort(array)
printArray("Sorted array is : ", array)
val index = Arrays.binarySearch(array, 2)
println("Element 2 found @ $index")
}
Sorted array is : -5, -4, -3, -2, -1, 1, 2, 3, 4, 5
Element 2 found @ 6
Description:Element 2 found @ 6
In the above program to sort an array in kotlin, we have used a user-defined method printArray() to sort and print the array. To sort an array we have used java.util.arrays.sort() method. To find an element in the sorted array, we have used java.util.Arrays.binarySearch(int[], int) method.
0 Comments