Created
March 28, 2020 21:50
-
-
Save YusufAbdelaziz/3626a49fd696abd2d4629cd05667349b to your computer and use it in GitHub Desktop.
Divide and conquer --> question 1
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
import java.io.*; | |
import java.util.*; | |
public class problemSolving { | |
static int binarySearch(int[] a, int x, int left, int right) { | |
if (left > right) { | |
return -1; | |
} | |
int middle = left + ((right - left) / 2); | |
if (a[middle] == x) { | |
return middle; | |
} else if (a[middle] > x) { | |
return binarySearch(a, x, left, middle - 1); | |
} else { | |
return binarySearch(a, x, middle + 1, right); | |
} | |
} | |
public static void main(String[] args) { | |
FastScanner scanner = new FastScanner(System.in); | |
int n = scanner.nextInt(); | |
int[] a = new int[n]; | |
for (int i = 0; i < n; i++) { | |
a[i] = scanner.nextInt(); | |
} | |
int m = scanner.nextInt(); | |
int[] b = new int[m]; | |
for (int i = 0; i < m; i++) { | |
b[i] = scanner.nextInt(); | |
} | |
for (int i = 0; i < m; i++) { | |
System.out.print(binarySearch(a, b[i], 0, a.length - 1) + " "); | |
} | |
} | |
static class FastScanner { | |
BufferedReader br; | |
StringTokenizer st; | |
FastScanner(InputStream stream) { | |
try { | |
br = new BufferedReader(new InputStreamReader(stream)); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
String next() { | |
while (st == null || !st.hasMoreTokens()) { | |
try { | |
st = new StringTokenizer(br.readLine()); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return st.nextToken(); | |
} | |
int nextInt() { | |
return Integer.parseInt(next()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment