Skip to content

Commit dd0f055

Browse files
abdulwdthuva4
authored andcommitted
Add binary search in Kotlin (thuva4#435). (thuva4#436)
1 parent 4eabf6a commit dd0f055

2 files changed

Lines changed: 39 additions & 3 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
fun IntArray.binarySearch(lowerIndex: Int, upperIndex: Int, x: Int): Int {
2+
val arr = this
3+
if (upperIndex >= lowerIndex) {
4+
val mid = lowerIndex + (upperIndex - lowerIndex) / 2
5+
6+
// If the element is found
7+
if (arr[mid] == x)
8+
return mid
9+
10+
/* If the element is smaller than mid, then it can only be present in left subarray
11+
else the element can only be present in right subarray */
12+
return if (arr[mid] > x) binarySearch(lowerIndex, mid - 1, x)
13+
else binarySearch(mid + 1, upperIndex, x)
14+
}
15+
// We reach here only when the element is not present in array
16+
return -1
17+
}
18+
19+
fun main(args: Array<String>) {
20+
println("Enter the size of array:")
21+
val n = readLine()!!.toInt()
22+
println("Enter the elements of array:")
23+
var arr = IntArray(n) { readLine()!!.toInt() }
24+
println("Enter a number to search:")
25+
val x = readLine()!!.toInt()
26+
arr = arr.sortedArray() // Sorting the array in ascending order
27+
println("Array in ascending order: ")
28+
for (l in arr)
29+
print("$l ")
30+
println()
31+
val result = arr.binarySearch(0, n - 1, x)
32+
if (result == -1)
33+
println("Element not present")
34+
else
35+
println("Element found at index $result")
36+
}

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ This repository contains examples of various algorithms which were written on di
55
## Implemented algorithms with languages:
66

77

8-
Language| Java | Python | Rust | C | C++ | JavaScript | Go | C# | Ruby | Swift | Racket | Perl | Crystal
9-
---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
8+
Language| Java | Python | Rust | C | C++ | JavaScript | Go | C# | Ruby | Swift | Racket | Perl | Crystal| Kotlin
9+
---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
1010
A*Search | | :+1: | | | :+1: | | | |
1111
BellmanFord | :+1: | | | | :+1: | | | |
1212
BestFirstSearch | :+1: | :+1: | | | | | | | :+1: |
1313
BinaryGCD | :+1: | | | | | | | | |
14-
BinarySearch | :+1: | :+1: | | :+1: | :+1: | :+1: | :+1: | | :+1: | :+1:
14+
BinarySearch | :+1: | :+1: | | :+1: | :+1: | :+1: | :+1: | | :+1: | :+1: | | | | :+1:
1515
Binary Search Modified | | | | :+1: | | | | |
1616
Bitap Algorithm | | :+1: | | | :+1: | | | |
1717
BreadthFirstSearch | :+1: | :+1: | | :+1: | | | | |

0 commit comments

Comments
 (0)