Problem:
Create a binary search app in java using iteration and recursion.
Note: Binary search only works with sorted list of numbers.
Note: Binary search only works with sorted list of numbers.
Output:
Enter a target int
4
Target found iteratively!
Target found recursively!
4
Target found iteratively!
Target found recursively!
Solution:
package binarySearchApp;
import java.util.Scanner;
public class BinarySearchApp {
public static void main(String[] args) {
int[] pool = {4,8,9,13,17,22};
int target;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a target int");
target = scan.nextInt();
boolean found;
//********************iterative version *************************
found = binarySearch_iter(pool, target);
if (found)
System.out.println("Target found iteratively!");
else
System.out.println("Target not found iteratively!");
//********************recursive version *************************
found = binarySearch_rec(pool, target, 0, pool.length-1);
if (found)
System.out.println("Target found recursively!");
else
System.out.println("Target not found recursively!");
}
//********************iterative method *************************
private static boolean binarySearch_iter (int[] pool, int target) {
int min = 0, max = pool.length-1, mid;
boolean found = false;
while (!found && min <= max) {
mid = (min+max)/2;
if (pool [mid] == target)
found = true;
else if (pool [mid] < target)
min = mid +1;
else
max = mid -1;
}
return found;
}
//********************recursive method *************************
private static boolean binarySearch_rec (int[] pool, int target, int min, int max) {
if (min > max)
return false;
else {
int mid = (min + max)/2;
if (pool[mid] == target)
return true;
else if (pool[mid] < target)
return binarySearch_rec (pool, target, mid+1, max);
else
return binarySearch_rec (pool, target, min, mid-1);
}
}
}