Kotlin Algorithms
What are Algorithms?
Algorithms are step-by-step instructions or procedures designed to solve specific problems or perform tasks. In programming, algorithms provide a clear and logical pathway to manipulate data and produce desired outcomes efficiently. Whether sorting a list, searching for an element, or performing mathematical computations, algorithms are at the core of software functionality.
Algorithms in Kotlin
Kotlin, with its modern syntax and support for functional programming, enables clear and concise implementation of algorithms.
Many classical algorithms can be expressed using Kotlin's features like extension functions, higher-order functions, and collection APIs.
The Kotlin standard library includes useful methods such as sortedBy, filter, map, and
binarySearch that simplify algorithmic tasks. Understanding and applying algorithms efficiently in Kotlin leads to performant
and readable code. Kotlin’s expressive syntax and built-in functions make algorithm implementation elegant and accessible.
1. Searching Algorithms
Linear Search
fun linearSearch(arr: List, target: Int): Int {
for ((index, value) in arr.withIndex()) {
if (value == target) return index
}
return -1
}
Binary Search (for sorted lists)
fun binarySearch(arr: List, target: Int): Int {
var left = 0
var right = arr.size - 1
while (left <= right) {
val mid = (left + right) / 2
when {
arr[mid] == target -> return mid
arr[mid] < target -> left = mid + 1
else -> right = mid - 1
}
}
return -1
}
2. Sorting Algorithms
Bubble Sort
fun bubbleSort(arr: MutableList) {
for (i in 0 until arr.size - 1) {
for (j in 0 until arr.size - i - 1) {
if (arr[j] > arr[j + 1]) {
val temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
}
Kotlin Built-in Sort
val numbers = listOf(5, 2, 9, 1, 5, 6)
val sorted = numbers.sorted()
println(sorted) // Output: [1, 2, 5, 5, 6, 9]
3. Recursion Example: Factorial
fun factorial(n: Int): Int {
return if (n == 0) 1 else n * factorial(n - 1)
}
4. Kotlin-specific Functional Algorithms
Kotlin supports functional programming paradigms which are useful in concise algorithm design.
Filter Even Numbers
val numbers = listOf(1, 2, 3, 4, 5, 6)
val evens = numbers.filter { it % 2 == 0 }
println(evens) // Output: [2, 4, 6]