Hallo Leute, wie kann ich die folgende Binary Search ausführen? Die Logik die ich geschrieben gibt mir leider keine Ausgabe, ich würde auch gern den Grund dafür wissen.
Java:
//https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
public class FirstAndLastPosition {
public static void main(String[] args) {
}
public int[] searchRange(int[] nums, int target) {
//If the value is not in range return {-1,-1}
//0 index: -1 -> start
//1 index: -1 -> end
int[] ans = {-1,-1};
int[] nums2 = {19,19,19,20,21,22,23};
target = 19;
//checking for start value
int start = search(nums2, target, true);
//checking for end value
int end = search(nums, target, false);
System.out.println(start);
System.out.println(end);
//Updating the answer. In other words, updating int[] ans = {-1,-1}
ans[0] = start;
ans[1] = end;
//If the value is not in range return {-1,-1}
return ans;
}
//this function just returns the index value of target
static int search(int[] nums, int target, boolean findStartIndex) {
//my potential answer is initially -1
int ans = -1;
int start = 0;
int end = nums.length -1;
while (start<=end) {
int mid = start + (end - start) / 2;
if (target < nums[mid]) {
end = mid-1;
} else if (target > nums[mid]) {
start = mid+1;
} else {
//potential ans found
ans = mid;
//if more target values are on the left -> end = mid - 1;
if (findStartIndex == true) {
end = mid - 1;
//if more target values are on the right -> start = mid + 1;
} else {
start = mid + 1;
}
}
}
//my potential answer is initially -1
return ans;
}
//prints Process finished with exit code 0
}