Skip to content

Instantly share code, notes, and snippets.

@rungxanh1995
Last active April 22, 2022 01:16
Show Gist options
  • Save rungxanh1995/5a7f77d702be0dff47402f5541656e68 to your computer and use it in GitHub Desktop.
Save rungxanh1995/5a7f77d702be0dff47402f5541656e68 to your computer and use it in GitHub Desktop.
Binary Search algorithm in Java, Kotlin, Swift, C#, Python3

Problem

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.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Constraints:

  • 1 <= nums.length <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All the integers in nums are unique.
  • nums is sorted in ascending order.
public class Solution
{
public static int Search(int[] nums, int target)
{
if (nums.Length >= 1)
{
int low = 0;
int high = nums.Length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (nums[mid].Equals(target)) return mid;
if (nums[mid] < target) low = mid + 1;
else high = mid - 1;
}
}
return -1;
}
}
class Solution {
int search(int[] nums, int target) {
if (nums.length >= 1) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) low = mid + 1;
else high = mid - 1;
}
}
return -1;
}
}
class Solution {
companion object {
fun search(nums: IntArray, target: Int): Int {
if (nums.isNotEmpty()) {
var low = 0
var high = nums.size - 1
while (low <= high) {
val mid = (low + high) / 2
if (nums[mid] == target) return mid
else if (nums[mid] < target) low = mid + 1
else high = mid - 1
}
}
return -1
}
}
}
class Solution:
@staticmethod
def search(nums: List[int], target: int) -> int:
if len(nums) >= 1:
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
class Solution {
class func search(_ nums: [Int], _ target: Int) -> Int {
guard !nums.isEmpty else { return -1 }
var low = 0, high = nums.count - 1
while (low <= high) {
let mid = (low + high) / 2
if nums[mid] == target { return mid }
else if nums[mid] < target { low = mid + 1 }
else { high = mid - 1 }
}
return -1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment