You are on page 1of 4

Blue Ridge Public School

Class X – Computer Applications

A.Y. 2023-24

ASSIGNMENT – 12

1. Write a program in Java to search an element in a descending order


array using binary search technique:

import java.util.*;
public class ArrDescBinarySearch
{
int [] arr;
int ns;

public void input(){


Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array");
int n = sc.nextInt();
arr = new int[n];

System.out.println("Enter the integer elements of


the array in a descending order:");
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
}

System.out.println("Enter the number to be searched


in the array:");
ns = sc.nextInt();

}//end of input method


public void binarySearch(){

boolean isFound = false;


int pos = 0, beg = 0, end = arr.length-1, mid = 0;
while(beg <= end){
mid = (beg + end)/2;
if(ns == arr[mid]){
isFound = true;
pos = mid+1;
break;
}
else if(ns < arr[mid])//for descending array
beg = mid + 1;
else
end = mid-1;

}
if(isFound){
System.out.println("Search Number " + ns
+ " found at position "
+ pos + " in the array");
}
else{
System.out.println("Search Number " + ns
+ " not found in the
array");
}
} //end of binary search method
public static void main(String [] args){
ArrDescBinarySearch obj = new ArrDescBinarySearch();
obj.input();
obj.binarySearch();
}//main method ends
}//program ends

OUTPUT

Enter the size of the array:


10
Enter the integer elements of the array in a descending order:
57
43
36
33
28
25
23
19
14
6
Enter the number to be searched in the array:
23
Search number 23 is found at position 7 in the array
Variable Name Data type Description

n, ns, i, pos, beg, end, int stores integer values


mid

isFound boolean stores a boolean value

arr int [] stores an integer array

You might also like