Page 92 - CTS - CSA TP - Volume 2
P. 92

COMPUTER SOFTWARE APPLICATION - CITS




           6  mid = (start+end)/2

           7  if array[ mid ] == target then return mid
           8  if array[ mid ] < target then start = mid+1
           9  if array[ mid ] > target then end = mid-1
           10 if start<=end then goto step 6

           11 return -1 as Not element found
           12 Exit
           Here’s a Java program that allows the user to input array elements through the keyboard and performs binary
           search:
           import java.util.Scanner;
           public class BinarySearch {
               public static int binarySearch(int[] arr, int target) {
                   int left = 0;
                   int right = arr.length - 1;



                   while (left <= right) {
                       int mid = left + (right - left) / 2;


                       if (arr[mid] == target)
                           return mid;
                       else if (arr[mid] < target)
                           left = mid + 1;
                       else
                           right = mid - 1;
                   }


                   return -1;
               }

               public static void main(String[] args) {
                   Scanner scanner = new Scanner(System.in);


                   // Prompt the user to enter the size of the array
                   System.out.print(“Enter the size of the array: “);
                   int size = scanner.nextInt();


                   // Create an array of the specified size
                   int[] arr = new int[size];


                   // Prompt the user to enter array elements

                   System.out.println(“Enter the elements of the array :”);
                   for (int i = 0; i < size; i++) {





                                                           77
                                CITS : IT & ITES - Computer Software Application - Exercise 93
   87   88   89   90   91   92   93   94   95   96   97