Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to efficiently find the index of smallest value that is larger than some target within a sorted array, in Java?

/*
	This is an implementation that finds the idx of 
	smallest value that is larger than some target value.
	The method returns length of array if no such value 
	exist in the array.

	Let n be the number of binary tree nodes
	Time complexity: O(log2n) 
	Space complexity: O(1)
*/
public class SmallestLargerThanTarget {
	private static int getIdxSmallestLargerVal(int[] arr, int target) {
		// If target is larger than largest value in arr
		// Return length of arr.
		if (target > arr[arr.length - 1]) {
			return arr.length;
		}
		int middle, left = 0, right = arr.length - 1;
		// Find through binary search the smallest idx
		// where arr[idx] > target
		while (left < right) {
			middle = left + (right - left) / 2;
			if (arr[left] <= target) {
				left = middle;
			} else {
				right = middle - 1;
			}
		}

		return left;
	}
	public static void main(String[] args) {
		int[] arr = { 1, 4, 9, 12, 13, 16 };
		int target = 8;
		int result = getIdxSmallestLargerVal(arr, target);
		System.out.println(result); // 2
		target = 17;
		result = getIdxSmallestLargerVal(arr, target);
		System.out.println(result); // 6
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: java read file bufferedreader 
Java :: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.kodakjhelum.ItemFragment: make sure class name exists 
Java :: get value textfield java 
Java :: android send parameters with intent 
Java :: multiply two strings 
Java :: How to create a disjoint-set data structure, in Java? 
Java :: find shortest string in array java 
Java :: spigot despawn entity 
Java :: dupplicate classes android 
Java :: get time stamp java 
Java :: parallel sorting in java 8 
Java :: simple java program 
Java :: static and final in java 
Java :: return day from date in java 
Java :: java array to list 
Java :: char equals java 
Java :: how to create immutable list java 
Java :: how to print multiple lines in java 
Java :: system.out.print two dimensional array 
Java :: java get input 
Java :: java shutdown hook 
Java :: how to wait in java 
Java :: write json file java 
Java :: java join list as string 
Java :: turn java code to .exe 
Java :: java map not null 
Java :: java insert into arraylist 
Java :: inline arraylist initialization java 
Java :: java datetime now 
Java :: java get folder content 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =