数组的练习
1.要求根据数组元素查找出该元素第一次在数组中出现的索引
方法1:遍历数组挨个去查
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
int arr[]={1,2,54,32,122,3,12,1};
//根据元素查找出该元素第一次在数组中出现的索引
int index= getIIndexByEIE(arr,1);
System.out.println("该元素第一次在数组中出现的索引是:"+index);
}
private static int getIIndexByEIE(int[] arr,int ale){
//遍历数组,去查找
for (int i = 0; i < arr.length ; i++) {
if (ale==arr[i]){
return i;
}
}
return -1;//如果我们没有找到这个元素就返回-1
}
}
//结果:该元素第一次在数组中出现的索引是:0
方法2:二分查找
前提:该数组的元素必须有序
思想:每一次查找中间的元素,比较大小就能减少一半的元素
public class Application {
public static void main(String[] args) {
int arr[]={3,9,11,12,23,32};
int index=getCount(arr,9);
System.out.println("所查找的索引值为"+index);
}
private static int getCount(int[]arr,int ale){
int minIndex=0;
int maxIndex= arr.length-1;
int centerIndex=(maxIndex+minIndex)/2;
while (minIndex<=maxIndex){
if (ale==arr[centerIndex]){
return centerIndex;
}else if(ale>arr[centerIndex])
{
minIndex=centerIndex+1;
}else if(ale<arr[centerIndex]){
maxIndex=centerIndex-1;
}
centerIndex=(maxIndex+minIndex)/2;
}
return -1;//如果没有找到返回-1
}
}
这篇博客探讨了两种在Java中查找数组元素索引的方法。首先介绍了基础的遍历数组法,通过循环检查每个元素来找到目标元素的索引。接着,讨论了在有序数组中使用二分查找的高效策略,它通过不断缩小搜索范围来快速定位目标元素的索引。这两种方法各有适用场景,对于无序数组,遍历是必要选择;而对于有序数组,二分查找能显著提高效率。

1280

被折叠的 条评论
为什么被折叠?



