Book Image

Hands-On Data Structures and Algorithms with Kotlin

By : Chandra Sekhar Nayak, Rivu Chakraborty
Book Image

Hands-On Data Structures and Algorithms with Kotlin

By: Chandra Sekhar Nayak, Rivu Chakraborty

Overview of this book

Data structures and algorithms are more than just theoretical concepts. They help you become familiar with computational methods for solving problems and writing logical code. Equipped with this knowledge, you can write efficient programs that run faster and use less memory. Hands-On Data Structures and Algorithms with Kotlin book starts with the basics of algorithms and data structures, helping you get to grips with the fundamentals and measure complexity. You'll then move on to exploring the basics of functional programming while getting used to thinking recursively. Packed with plenty of examples along the way, this book will help you grasp each concept easily. In addition to this, you'll get a clear understanding of how the data structures in Kotlin's collection framework work internally. By the end of this book, you will be able to apply the theory of data structures and algorithms to work out real-world problems.
Table of Contents (16 chapters)
Free Chapter
Section 1: Getting Started with Data Structures
Section 2: Efficient Grouping of Data with Various Data Structures
Section 3: Algorithms and Efficiency
Section 4: Modern and Advanced Data Structures

Linear search

When we try to find an element in a collection by checking each element of the collection one by one, we refer to this way of searching as a linear search. We can perform a linear search for both unordered and ordered collections.

Linear search in an unordered collection

As the elements in an unordered collection are not in a clear and logical order, we've to check each element until we find the required one. The code for such a linear search will look like the following:

fun <E> Collection<E>.linearSearch(element: E): Int {
for ((index, value) in this.withIndex()) {
if (value == element) return index
return -1

One thing to note here is that the function is defined as an extension...