-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchIterative
More file actions
30 lines (27 loc) · 868 Bytes
/
BinarySearchIterative
File metadata and controls
30 lines (27 loc) · 868 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.company;
/*
* Given an array of integers nums which is sorted in ascending order,
* and an integer target, write a function to search target in nums.
* If target exists, then return its index. Otherwise, return -1.
* You must write an algorithm with O(log n) runtime complexity.
*/
public class Main {
public static int search(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while (left <= right){
int index = (left + right)/2;
if (nums[index] == target)
return index;
if (nums[index] > target)
right = index - 1;
else
left = index + 1;
}
return -1;
}
public static void main(String[] args) {
int array[] = {-1,0,3,5,9,12};
System.out.println(search(array,2));
}
}