You are on page 1of 4

19BCE0994_SHRUTI GARG

LAB CAT 1

NAME: SHRUTI GARG REG NO: 19BCE0994


DATE: 24/03/2021 SLOT: L19 + L20

5. Write a method to implement the binary search. Use a package that has
the class sort with a method void bubble_sort(double[] array) to perform a
bubble sort public void search(double[] array) .
Write a test program that prompts the user to enter n numbers, and a search
element. Invokes this method to return the position of the search element.
Code:
//package used
package sortingpkg;

public class sort {


public void bubble_sort(double[] array){
double temp=0;

for(int i=0; i<array.length; i++){


for(int j=i+1; j< array.length; j++){
if(array[i]>array[j]){
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}

}
}

package labcat;

import sortingpkg.*;

import java.util.Scanner;

public class SHRUTI_19BCE0994 {


public static void binarySearch(double arr[], double num,int n){
boolean key= false;
int m;
int l=0;
int u=n-1;
while(l<u){
19BCE0994_SHRUTI GARG

m=(l+u)/2;
if(num==arr[m]) {
System.out.println("Number found at " + (m+1) + " position.");
key=true;
break;
}
if(num>arr[m])
l=m+1;
else
u=m-1;

}
if(!key) {
System.out.println("Number not found!!");
}
}

public static void main(String args[]){


int n;
double arr[];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements: ");
n= sc.nextInt();
arr= new double[n];
System.out.println("Enter "+n+" numbers: ");
for(int i=0; i< arr.length; i++){
arr[i]=sc.nextDouble();
}

double element;
System.out.println("Enter the element to be searched:");
element= sc.nextDouble();

sort sorting =new sort();


sorting.bubble_sort(arr);
binarySearch(arr,element,n);
}
}
19BCE0994_SHRUTI GARG
19BCE0994_SHRUTI GARG

Output:

You might also like