Java程序验证数组中是否存在给定元素


给定一个数组和一个作为输入的元素,编写一个Java程序来检查该元素是否存在于给定数组中。您可以使用搜索算法查找数组中的任何元素。在本文中,我们将使用线性搜索和二分搜索算法。

使用线性搜索算法

在这种方法中,请按照以下步骤验证数组中是否存在给定元素:

  • 使用for循环遍历数组。
  • 将每个元素与所需元素进行比较。
  • 如果找到,则返回索引。

示例

以下Java程序演示了如何使用线性搜索算法检查数组中是否存在给定元素。

import java.util.*;
public class ArraySearch {
   public static void main(String[] args) {
      int[] myArray = {23, 93, 56, 92, 39};
      System.out.println("Elements of the given array: " + Arrays.toString(myArray));
      int searchVal = 39;
      System.out.println("The value to be searched: " + searchVal);
      // checking if the element is present
      for (int i =0 ; i < myArray.length; i++) {
         if (myArray[i] == searchVal) {
            System.out.println("The index of element " + searchVal + " is : " + i);
         }
      }
   }
}

执行此代码时,将显示以下输出:

Elements of the given array: [23, 93, 56, 92, 39]
The value to be searched: 39
The index of element 39 is : 4

使用Arrays.binarySearch()方法

Arrays类java.util包提供了一个名为binarySearch()的方法,此方法接受一个已排序的数组和一个要搜索的值,并返回该元素在数组中的索引。

示例

在此示例中,我们使用binarySearch()方法来验证数组中是否存在给定元素。

import java.util.Arrays;
import java.util.Scanner;
public class ArraySearch {
   public static void main(String[] args) {
      int[] myArray = {23, 93, 56, 92, 39};
      System.out.println("Elements of the given array: " + Arrays.toString(myArray));
      int searchVal = 39;
      System.out.println("The value to be searched: " + searchVal);
      //Sorting the array
      Arrays.sort(myArray);
      System.out.println("The sorted int array is:");
      for (int number : myArray) {
         System.out.print(number+" ");
      }
      System.out.println(" ");
      int retVal = Arrays.binarySearch(myArray,searchVal);
      System.out.println("Element found");
      System.out.println("The index of element in the sorted array: " + retVal);
   }
}

运行上述代码后,将显示以下结果:

Elements of the given array: [23, 93, 56, 92, 39]
The value to be searched: 39
The sorted int array is:
23 39 56 92 93  
Element found
The index of element in the sorted array: 1 

更新于: 2024年7月31日

1K+ 次浏览

开启你的职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.