#Issues with logic and or making a variable that holds an int negative incorrectly
6 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @gaunt junco! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
import java.io.FileReader;
import java.io.IOException;
public class BinarySearch {
public static int search(int key, int[] a) {
return search(key, a, 0, a.length - 1);
}
public static int search(int key, int[] a, int lo, int hi) {
int result = -1; // Initialize result to -1
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) {
hi = mid - 1; // Adjust the upper bound
} else if (key > a[mid]) {
lo = mid + 1; // Adjust the lower bound
} else {
// Key found; update result and continue searching to the right
result = mid;
lo = mid + 1;
}
}
// If result is not updated, key not found; return -i where i is the largest index less than key
if (result == -1) {
return -lo - 1;
}
return result; // Key found; return the largest index where a[i] is equal to key
}
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java BinarySearch <input_file> <search_key>");
System.exit(1);
}
String inputFile = args[0];
int key = Integer.parseInt(args[1]);
try {
// Read the input file and parse elements
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String[] elements = reader.readLine().split(" ");
int[] a = new int[elements.length];
for (int i = 0; i < elements.length; i++) {
a[i] = Integer.parseInt(elements[i]);
}
reader.close();
int result = search(key, a);
// Output the result
System.out.println(result);
} catch (IOException e) {
System.err.println("Error reading the input file: " + e.getMessage());
System.exit(1);
}
}
}```
input.txt file: