0% found this document useful (0 votes)
3 views3 pages

public class BinarySearch

The document contains a Java implementation of a binary search algorithm within a class called BinarySearch. It includes methods for searching the first index of a specified key in a sorted array. The Main class handles user input for array size and search value, generates a random array, sorts it, and utilizes the BinarySearch class to find the key's index.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

public class BinarySearch

The document contains a Java implementation of a binary search algorithm within a class called BinarySearch. It includes methods for searching the first index of a specified key in a sorted array. The Main class handles user input for array size and search value, generates a random array, sorts it, and utilizes the BinarySearch class to find the key's index.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

public class BinarySearch {

private int[] array;

public BinarySearch(int[] array) {


this.array = array;
}

public int searchFirstIndex(int key) {


int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = (right - left) / 2 + left; // ngoặc đel đóng
if (array[mid] == key) {
return mid;
} else if (array[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
import java.util.Arrays;
public class Main {

public static void main(String[] args) {


int number = Validator.getInt("Enter number of array", "Please enter number
> 0",
"Please enter integer number", 1, Integer.MAX_VALUE);

int key = Validator.getInt("Enter search value", "Error range!",


"Please enter integer number", Integer.MIN_VALUE,
Integer.MAX_VALUE);

Array array = new Array(number);


int[] randomArray = null;
try {
randomArray = array.getRandomArray(number);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
// sort Array
Arrays.sort(randomArray);
System.out.println("The array: " + array.toString());
BinarySearch search = new BinarySearch(randomArray);
int index = search.searchFirstIndex(key);
if (index == -1) {
System.out.println("Cannot find key!");
} else {
System.out.println("Found " + key + " at index: " + index);
}
}
}

You might also like