Introduction to Algorithms and Data Structures in Kotlin
Kotlin is a modern programming language that combines conciseness and power. Learning algorithms and data structures in Kotlin opens the path to writing efficient and scalable code. Whether you are developing Android applications, backend services, or desktop programs, understanding basic structures and algorithms is a mandatory skill for any professional developer.
In this article, we will break down key data structures and algorithms in Kotlin with practical code examples. You will learn how to implement sorting, searching, working with lists, stacks, queues, trees, and graphs.
1. Basic Data Structures in Kotlin
1.1. Arrays and Lists
In Kotlin, arrays are represented by the Array type, and dynamic lists by List and MutableList. Lists are the most commonly used data structure.
fun main() { // Immutable list val list: List<Int> = listOf(1, 2, 3, 4, 5) // Mutable list val mutableList: MutableList<Int> = mutableListOf(10, 20, 30) mutableList.add(40) mutableList.removeAt(0) println(mutableList) // [20, 30, 40]}1.2. Stack
A stack operates on the LIFO (Last In, First Out) principle. In Kotlin, a stack can be implemented using ArrayDeque.
fun stackExample() { val stack = ArrayDeque<String>() stack.addLast(\"First\") stack.addLast(\"Second\") stack.addLast(\"Third\") println(stack.removeLast()) // Third println(stack.removeLast()) // Second println(stack.removeLast()) // First}1.3. Queue
A queue operates on the FIFO (First In, First Out) principle. The implementation also uses ArrayDeque.
fun queueExample() { val queue = ArrayDeque<Int>() queue.addLast(1) queue.addLast(2) queue.addLast(3) println(queue.removeFirst()) // 1 println(queue.removeFirst()) // 2 println(queue.removeFirst()) // 3}1.4. Linked List
A linked list is a sequence of nodes, each containing data and a reference to the next node. Let's implement a simple singly linked list.
class Node<T>(var value: T, var next: Node<T>? = null)
class LinkedList<T> { private var head: Node<T>? = null fun add(value: T) { val newNode = Node(value) if (head == null) { head = newNode } else { var current = head while (current?.next != null) { current = current.next } current?.next = newNode } } fun printAll() { var current = head while (current != null) { print(\"${current.value} \") current = current.next } println() }}
fun main() { val list = LinkedList<Int>() list.add(10) list.add(20) list.add(30) list.printAll() // 10 20 30}2. Sorting Algorithms in Kotlin
2.1. Bubble Sort
A simple but inefficient algorithm. Complexity O(n²).
fun bubbleSort(arr: MutableList<Int>) { val n = arr.size for (i in 0 until n - 1) { for (j in 0 until n - i - 1) { if (arr[j] > arr[j + 1]) { val temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } }}
fun main() { val numbers = mutableListOf(64, 34, 25, 12, 22, 11, 90) bubbleSort(numbers) println(numbers) // [11, 12, 22, 25, 34, 64, 90]}