【发布时间】:2021-11-25 05:01:59
【问题描述】:
我有一个数组,我使用线性搜索搜索一个元素。但我想 在我得到结果的步骤后数一数。但我无法 计算步骤,我只能从 数组,但是找不到步骤。 线性搜索.java
public class ArrayRotation {
public static int linearSearch(int []arr,int x){
int n = arr.length-1;
for (int i=0;i<=n;i++){
if (arr[i]== x)
return i;
}
return -1;
}
public static void main(String[] args) {
ArrayRotation arrRotation = new ArrayRotation();
int arr[]={4,56,44,152,54,845};
int x = 26;
int result = linearSearch(arr,x);
if (result == -1)
System.out.println("searching element not Present in this array");
else
System.out.println("Searching element present at the index position" +result);
}
}
【问题讨论】:
-
既然您正在执行线性搜索并返回项目的索引,那么您返回的内容不也表明步数吗?
Number of steps = value returned + 1
标签: java linear-search