一個遞迴程式用來線上性陣列中找到一個元素。


這是一個 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("Enter the required size of the array: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      System.out.println("Enter the elements of the array one by one ");
      for(int i=0; i<size; i++){
         myArray[i] = s.nextInt();
      }
      System.out.println("Enter the element to be searched: ");
      int target = s.nextInt();
      boolean bool = searchArray(myArray, target ,size);
      if(bool){
         System.out.println("Element found");
      }else{
         System.out.println("Element not found");
      }
   }
}

輸出

Enter the required size of the array:
5
Enter the elements of the array one by one
14
632
88
98
75
Enter the element to be searched:
632
Element found

更新時間: 2019 年 7 月 30 日

840 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告