Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to find a target element within a search pool using binary search?

public class BinarySearch {
	/*
	 * Searching is the process of finding a target
	 * element within a search pool. Binary search
	 * is used when the search pool is sorted.
	 */
	public static void main(String[] args) {
		int[] searchPool = { 1, 3, 5, 10, 12, 14 };
		int target = 12;
		System.out.println(binarySearch(searchPool, target)); // true
		target = 13;
		System.out.println(binarySearch(searchPool, target)); // false
	}

	private static boolean binarySearch(int[] pool, int target) {
		// pool is assumed to be sorted in ascending order
		int left = 0, right = pool.length - 1;
		int middle;
		boolean found = false;
		// Keep searching until either you find element or not
		while (!found && left <= right) {
			middle = left + (right - left) / 2;
			// Repeatedly check middle element
			if (pool[middle] == target) {
				found = true;
			} else if (pool[middle] < target) {
				left = middle + 1;
			} else {
				right = middle - 1;
			}
		}
		return found;
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: inject in jsp 
Java :: star pattern in java 
Java :: pyramid star pattern in java 
Java :: java Date get today date 
Java :: jpa validation string only number 
Java :: java console write 
Java :: how to write custom message for repeat password in joi 
Java :: play ringtone android in infinite loop 
Java :: android run background service on startup 
Java :: How to iterate over a list in Java? 
Java :: Spring Boot Hibernate remove underscore naming strategy 
Java :: how to print arraylist 
Java :: afficher texte java 
Java :: spring xml 
Java :: change material fab color android 
Java :: dagger kapt dependency and plugin 
Java :: create map java 
Java :: why java is secure 
Java :: java string multiply 
Java :: convert set to list java 
Java :: how to iterate over a string in java 
Java :: reverse string in java 
Java :: java selenium select 
Java :: check if jcheckbox is checked java 
Java :: how to add to a date in android 
Java :: spring boot jpa in clause 
Java :: what is final in java 
Java :: How to determine if a given binary tree is a binary search tree, in Java? 
Java :: isnumber java 
Java :: java get random char from alphabet 
ADD CONTENT
Topic
Content
Source link
Name
9+2 =