Java递归程序线性查找数组中的元素
以下是一个Java程序,用于线性查找数组中的元素。
示例
import java.util.Scanner;
public class SearchingRecursively {
public static boolean searchArray(int[] myArray, int element, int size){
if (size == 0){
return false;
}
if (myArray[size-1] == element){
return true;
}
return searchArray(myArray, element, size-1);
}
public static void main(String args[]){
System.out.println("输入所需的数组大小: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
System.out.println("逐一输入数组的元素 ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
}
System.out.println("输入要搜索的元素: ");
int target = s.nextInt();
boolean bool = searchArray(myArray, target ,size);
if(bool){
System.out.println("Element found");
}else{
System.out.println("Element not found");
}
}
}输出结果
输入所需的数组大小: 5 逐一输入数组的元素 14 632 88 98 75 输入要搜索的元素: 632 Element found
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短