Untitled
unknown
java
3 years ago
2.7 kB
8
Indexable
import java.util.Arrays;
import java.util.Scanner;
public class Binary {
private static void TitleBinarySearch() {
String line = "\n==================================================";
String title = "B I N A R Y S O R T";
int length = (line.length() + title.length()) / 2;
String centeredTitle = String.format("%" + length + "s", title).replace(' ', ' ');
centeredTitle = String.format("%-" + length + "s", centeredTitle); // left align
System.out.println(line + "\n" + centeredTitle + line);
}
public void displayBinary() {
TitleBinarySearch();
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter the Array Size: ");
int n;
n = sc.nextInt();
int[] ray = new int[n];
System.out.print("\nPlease Enter the Elements of the Array: ");
for (int i = 0; i < n; i++) {
ray[i] = sc.nextInt();
}
Arrays.sort(ray);
System.out.println("\nSorted array:" + Arrays.toString(ray));
System.out.print("\nPlease Enter the Key Value to be Searched: ");
int z;
z = sc.nextInt();
int high = ray.length - 1;
int result;
result = BinarySearch(ray, z, 0, high);
System.out.println("The Element is found at index " + result);
}
public static int BinarySearch(int[] ray, int z, int low, int high) {
while (low <= high) {
//int mid = low + (high - low) / 2;
int mid = (low + high) / 2;
System.out.println("Searching....");
System.out.print("[ ");
for(int i = 0; i < ray.length; i++){
if(ray[i] == ray[mid]){
System.out.print("(" + ray[mid] + "), ");
}
else if(i == ray.length - 1) {
System.out.print(ray[i] + " ");
}
else{
System.out.print(ray[i] + ", ");
}
}
System.out.println("]");
System.out.println("Middle = " + ray[mid]);
System.out.println("Left = " + ray[low]);
System.out.println("Right = " + ray[high]);
System.out.println("\n");
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (ray[mid] == z) {
return mid;
}
if (ray[mid] < z) {
low = mid + 1;
}
if (ray[mid] > z) {
high = mid - 1;
}
}
return low;
}
}Editor is loading...