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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短