File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff 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+ ---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
1010A* Search | | :+1 : | | | :+1 : | | | |
1111BellmanFord | :+1 : | | | | :+1 : | | | |
1212BestFirstSearch | :+1 : | :+1 : | | | | | | | :+1 : |
1313BinaryGCD | :+1 : | | | | | | | | |
14- BinarySearch | :+1 : | :+1 : | | :+1 : | :+1 : | :+1 : | :+1 : | | :+1 : | :+1 :
14+ BinarySearch | :+1 : | :+1 : | | :+1 : | :+1 : | :+1 : | :+1 : | | :+1 : | :+1 : | | | | : +1 :
1515Binary Search Modified | | | | :+1 : | | | | |
1616Bitap Algorithm | | :+1 : | | | :+1 : | | | |
1717BreadthFirstSearch | :+1 : | :+1 : | | :+1 : | | | | |
You can’t perform that action at this time.
0 commit comments