File tree 1 file changed +25
-0
lines changed
1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ un main(args: Array <String >) {
2
+ val input = readLine()!! .trim().split(" " ).map { it -> it.toInt() }.toIntArray() // to read an array (from user input)
3
+ val eleToSearch = readLine()!! .trim().toInt() // to read the element to be searched (from user input)
4
+ val pos = binarySearchIterative(input, eleToSearch)
5
+ if (pos >= 0 ) {
6
+ println (pos) // to print position at last
7
+ } else {
8
+ println (" Position not found" )
9
+ }
10
+ }
11
+
12
+ fun binarySearchIterative (input : IntArray , eleToSearch : Int ) : Int {
13
+ var low = 0
14
+ var high = input.size- 1
15
+ var mid: Int
16
+ while (low <= high) {
17
+ mid = (low + high)/ 2
18
+ when {
19
+ eleToSearch > input[mid] -> low = mid+ 1 // element is greater than middle element of array, so it will be in right half of array
20
+ eleToSearch == input[mid] -> return mid // found the element
21
+ eleToSearch < input[mid] -> high = mid- 1 // element is less than middle element of array, so it will be in left half of the array.
22
+ }
23
+ }
24
+ return - 1
25
+ }
You can’t perform that action at this time.
0 commit comments