Sunday, October 1, 2023
HomeAlgorithmsBinary Search using Kotlin - Searching Algorithms #1

Binary Search using Kotlin – Searching Algorithms #1

-

In this article, let us discuss one more Algorithm – Binary Search which is the most frequently asked Algorithms during Interviews. Let us discuss about it in brief and how to implement its algorithm using Kotlin Programming Language.

According to Wikipedia, A Binary Search is a search algorithm that finds the position of a target value within a sorted array. The algorithm compares the target element with the middle element of the array. If the target element is greater than middle element, the algorithm will be reapplied to the right of the array. If the target element is less than middle element, then the algorithm is again applied to the left of the array. Note that this algorithm is to be applied only on the sorted array.

Related Links

[adinserter block=”3″]

Advantages

Binary Search is significantly faster than that of Linear search. While Linear search takes O(n) time to search for an element in worst case, Binary search only takes O(log n) to search an element. For example, if there are more elements, it will significantly reduces the amount of time taken to find the element from the sorted array.

Algorithm

We will discuss here, the two ways of achieving Binary Search Implementation –

1. Binary Search through Iteration

Below gist shows us how to achieve the Algorithm through iteration. Here our goal is simple: Firstly to read the array and the element to be searched from the user input and print the position of element in the array. Here is the iterative implementation of the same. Code is commented wherever I find it necessary. Feel free to modify in gist / comment if anything more required.


package main.algorithms.searching
fun main(args: Array<String>) {
val input = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() // to read an array (from user input)
val eleToSearch = readLine()!!.trim().toInt() // to read the element to be searched (from user input)
val pos = binarySearchIterative(input, eleToSearch)
if(pos >= 0 ) {
println(pos) // to print position at last
} else {
println("Position not found")
}
}
fun binarySearchIterative(input: IntArray, eleToSearch: Int) : Int{
var low = 0
var high = input.size1
var mid:Int
while(low <= high) {
mid = low + ((high low) / 2)
when {
eleToSearch >input[mid] -> low = mid+1 // element is greater than middle element of array, so it will be in right half of array
eleToSearch == input[mid] -> return mid // found the element
eleToSearch < input[mid] -> high = mid1 //element is less than middle element of array, so it will be in left half of the array.
}
}
return 1
}

view raw

BinarySearch.kt

hosted with ❤ by GitHub

[adinserter block=”3″]
2. Binary Search through Recursion

Now we’ll see how to achieve the same through Recursion. Below gist shows the same:


package main.algorithms.searching
fun main(args: Array<String>) {
val input = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() // to read an array (from user input)
val eleToSearch = readLine()!!.trim().toInt() // to read the element to be searched (from user input)
val pos = binarySearchRecursive(input, eleToSearch, 0, input.size 1)
if(pos >= 0 ) {
println(pos) // to print position at last
} else {
println("Position not found")
}
}
fun binarySearchRecursive(input: IntArray, eleToSearch: Int, low:Int, high:Int): Int {
while(low <=high) {
val mid = (low + high) /2
when {
eleToSearch > input[mid] -> return binarySearchRecursive(input, eleToSearch, mid+1, high) // element is greater than middle element of array, so it will be in right half. Recursion will call the right half again
eleToSearch < input[mid] -> return binarySearchRecursive(input, eleToSearch, low, mid1) //element is less than middle element of array, so it will be in left half of the array. Recursion will call the left half again.
eleToSearch == input[mid] -> return mid // element found.
}
}
return 1
}

Feel free to suggest any modifications / feedback on the above implementation.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

LATEST POSTS

Packages in Java

Hello World! Today's blog is about packages in java. Here, we will learn about what are packages and how we can use packages along with...

House Robber Problem | Maximum Sum of non-adjacent elements

In this blog post, we will discuss about how to find maximum sum of Non-Adjacent elements. Since House Robber Problem is a typical DP Problem...
00:11:41

Check Array Formation Through Concatenation | Leetcode Problem 1640

In this video, we will explain Check Array Formation Through Concatenation, Leetcode's 1640th problem in 2 different approaches along with a coding solution. Problem statement You are given...

Binary Tree Traversals in Kotlin – PreOrder, InOrder and PostOrder Traversals

Binary Tree Traversals are most common Tree Problems in an Interview as well as Competitive Programming. They can be efficient while searching, inserting and deleting...

Follow us

1,358FansLike
10FollowersFollow
400SubscribersSubscribe

Most Popular