> 10. Binary Search in Java (for integers)
Arrays in Java: (Part 7)
One Dimensional Array Binary Search:
10. Binary Search in Java (for integers)
11. Binary Search in Java (for Strings)
- Example: Binary Search in Java (for Integers)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import java.util.Scanner; class search { public static void main(String args[]) { Scanner scan = new Scanner(System.in); System.out.println("Number of elements:"); int n = scan.nextInt(); int array[] = new int[n]; System.out.println("enter " + n + " values"); for (int i=0; i<n; i++){ array[i] = scan.nextInt(); } System.out.println("Enter key or value to search"); int key = scan.nextInt(); int first = 0; int last = n-1; int middle = (first+last)/2; while(first<=last) { if (array[middle]<key) { first=middle+1; } else if (array[middle]==key) { System.out.println(key + " found at location " + (middle+1)); break; } else{ last=middle-1; } middle=(first+last)/2; } if (first>last) System.out.println(key + " is not present in the array"); } } - Example: Binary Search in Java (for Strings)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import java.util.Scanner; class search { public static void main(String args[]) { Scanner scan = new Scanner(System.in); System.out.println("Number of elements:"); int n = scan.nextInt(); String array[] = new String[n]; System.out.println("enter " + n + " values"); for (int i=0; i<n; i++){ array[i] = scan.next(); } System.out.println("Enter key or value to search"); String key = scan.next(); int first = 0; int last = n-1; int middle = (first+last)/2; while(first<=last) { if (array[middle].compareTo(key)<0){ first=middle+1; } else if (array[middle].compareTo(key)==0) { System.out.println(key + " found at location " + (middle+1)); break; } else{ last=middle-1; } middle=(first+last)/2; } if (first>last) System.out.println(key + " is not present in the array"); } }
java computer programming basic examples
ReplyDeleteListing the File System Roots