Created
October 5, 2019 13:47
-
-
Save AmrAbuelhamd/bcd769096b4471366f3ee19fb73d9a11 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Java Program to illustrate reading from Text File | |
| // using Scanner Class | |
| import java.io.*; | |
| import java.util.Hashtable; | |
| import java.util.Scanner; | |
| public class Main { | |
| // Returns index of x if it is present in arr[l.. | |
| // r], else return -1 | |
| static int binarySearch(int arr[], int l, int r, int x) | |
| { | |
| if (r >= l) { | |
| int mid = l + (r - l) / 2; | |
| // If the element is present at the | |
| // middle itself | |
| if (arr[mid] == x) | |
| return mid; | |
| // If element is smaller than mid, then | |
| // it can only be present in left subarray | |
| if (arr[mid] > x) | |
| return binarySearch(arr, l, mid - 1, x); | |
| // Else the element can only be present | |
| // in right subarray | |
| return binarySearch(arr, mid + 1, r, x); | |
| } | |
| // We reach here when element is not present | |
| // in array | |
| return -2; | |
| } | |
| public static void main(String[] args) throws IOException { | |
| // pass the path to the file as a parameter | |
| Scanner sc = new Scanner(new File("input.txt")); | |
| int n; | |
| n = sc.nextInt(); | |
| int arr[]=new int[n]; | |
| for (int i=0; i<n ;i++){ | |
| arr[i] = sc.nextInt(); | |
| } | |
| int m; | |
| m = sc.nextInt(); | |
| int quers[] = new int[m]; | |
| // creating a hash table | |
| Hashtable<Integer, Integer> results = | |
| new Hashtable<>(); | |
| for (int i = 0; i < m; i++) | |
| { | |
| quers[i] = sc.nextInt(); | |
| results.put(quers[i], 0); | |
| } | |
| BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt")); | |
| int count = 0; | |
| for (int i = 0; i < m; i++) | |
| { | |
| int currentQuery = quers[i]; | |
| if (results.get(currentQuery)==0) { | |
| results.put(currentQuery,(binarySearch(arr, 0, n - 1, currentQuery) + 1)); | |
| count++; | |
| } | |
| writer.write(results.get(currentQuery)+"\n"); | |
| } | |
| //writer.write((int)count+"\n"); | |
| writer.close(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Щас бы на github постить elegiggle