Java 打印出阵列中重复数字的位置
因此,我正在编写一个二进制搜索方法来查找给定给它的数字在数组中的位置。回到那个位置。因此,每次我将数组中的数字与我正在搜索的数字进行比较时,都会打印出数组中的位置和该位置的数字。到目前为止,她是我的代码:Java 打印出阵列中重复数字的位置,java,arrays,search,duplicates,Java,Arrays,Search,Duplicates,因此,我正在编写一个二进制搜索方法来查找给定给它的数字在数组中的位置。回到那个位置。因此,每次我将数组中的数字与我正在搜索的数字进行比较时,都会打印出数组中的位置和该位置的数字。到目前为止,她是我的代码: public static int binSearch(int[] arr, int key) { int lo = 0; int hi = array.length - 1; while (lo <= hi) { int mid = lo + (
public static int binSearch(int[] arr, int key) {
int lo = 0;
int hi = array.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (key < arr[mid]) {
hi = mid - 1;
} else if (key > arr[mid]) {
lo = mid + 1;
}
else {
return mid;
}
}
return -1;
}
public static void main(String[] arg) {
int[] array = new int[] { 0, 1, 2, 2, 2, 3, 3, 4};
for ( int i = 0; i < array.length; i++ ) {
int index = Arrays.binarySearch(array, i);
System.out.println(array[i] + " at " + index);
}
}
我的预期产出是
0 at 0
1 at 1
2 at 2
2 at 3
2 at 4
3 at 5
3 at 6
4 at 7
4 at 8
谢谢你的帮助 将索引而不是元素传递给二进制搜索函数
试试这个
for ( int i = 0; i < array.length; i++ ) {
int index = binarySearch(array, array[i]);
System.out.println(array[i] + " at " + index);
}
使用二进制搜索生成您提到的输出有什么用?。要获得前面提到的输出,可以使用线性搜索。如果按照Arrays.binarySearch方法的要求对数组进行排序,则第一项的索引很容易找到,如下所示:
int index= Arrays.binarySearch(array, value);
负结果表示值不在数组中。现在,如果找到了它,并且您对其他索引感兴趣,您只需单步遍历该数组,直到该值不再匹配:
public static void printIndexes(int[] array, int value){
int index= Arrays.binarySearch(array, value);
if (index < 0){
return; // value not in array
}
while (index < array.length && array[index]==value){
System.out.println(value + " at " + index);
index++;
}
}
是否还有其他方法可以使用二进制搜索按预期打印输出?Thanks@Benj你为什么想要这样的东西。即使很清楚,线性搜索在找到第一个匹配项时也会停止。您只需打印紧跟索引的元素。你不需要搜索它
0 at 0
1 at 1
2 at 3
2 at 3
2 at 3
3 at 5
3 at 5
4 at 7
int index= Arrays.binarySearch(array, value);
public static void printIndexes(int[] array, int value){
int index= Arrays.binarySearch(array, value);
if (index < 0){
return; // value not in array
}
while (index < array.length && array[index]==value){
System.out.println(value + " at " + index);
index++;
}
}