我正在进行任务,程序应该打印出阵列中的位置和该位置的数字(使用线性搜索)。这是我到目前为止所得到的,但输出并非我的预期。
输出:
Number 0 Linear Search Index At 0
Number 1 Linear Search Index At 1
Number 2 Linear Search Index At 2
Number 2 Linear Search Index At 5
Number 2 Linear Search Index At 7
Number 3 Linear Search Index At 9
Number 3 Linear Search Index At 10
Number 4 Linear Search Index At -1
Number 4 Linear Search Index At 11
Number 5 Linear Search Index At 13
Number 6 Linear Search Index At 16
Number 8 Linear Search Index At 17
Number 8 Linear Search Index At 18
Number 9 Linear Search Index At 19
Number 9 Linear Search Index At -1
Number 9 Linear Search Index At 20
Number 10 Linear Search Index At 21
Number 11 Linear Search Index At -1
Number 12 Linear Search Index At -1
Number 13 Linear Search Index At -1
Number 15 Linear Search Index At 22
Number 16 Linear Search Index At 23
Number 20 Linear Search Index At 24
Number 21 Linear Search Index At 26
Number 22 Linear Search Index At 27
Number 22 Linear Search Index At -1
Number 23 Linear Search Index At 29
Number 24 Linear Search Index At 30
Number 24 Linear Search Index At 32
Number 26 Linear Search Index At -1
Number 27 Linear Search Index At 33
Number 27 Linear Search Index At -1
Number 28 Linear Search Index At -1
Number 30 Linear Search Index At -1
代码:
public class LinearSearch {
public int linearSearch(int[] array, int key) {
int size = array.length;
for ( int i = 0; i < size; i++ ) {
if ( array[i] == key ) {
return i;
}
}
return -1;
}
public static void main(String[] arg) {
int[] array = { 0, 1, 2, 2, 3, 3, 4, 4, 5, 6, 8, 8, 9, 9, 9, 10, 11, 12, 13, 15, 16, 20, 21, 22, 22, 23, 24, 24, 26, 27, 27, 28, 30};
LinearSearch search = new LinearSearch();
for (int i = 0; i < array.length; i++) {
System.out.println("Number " + array[i] + " " + " Linear Search Index" +
search.linearSearch(array, i));
}
}
}
任何帮助都会很棒!谢谢!
答案 0 :(得分:0)
尝试用linSearch.linearSearch(array, i))
linSearch.linearSearch(array, array[i]))
public static void main(String[] arg) {
int[] array = { 0, 1, 2, 2, 3, 3, 4, 4, 5, 6, 8, 8, 9, 9, 9, 10, 11, 12, 13, 15, 16, 20, 21, 22, 22, 23, 24, 24, 26,
27, 27, 28, 30 };
MyLinearSearch linSearch = new MyLinearSearch();
for (int i = 0 ; i < array.length ; i++) {
System.out.println("Number " + array[i] + " " + " Linear Search Index At "
+ linSearch.linearSearch(array, array[i]));
}
}