集册 Java实例教程 按顺序搜索数组中的项。

按顺序搜索数组中的项。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

531
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
按顺序搜索数组中的项。
/*来自 时代Java公众号*/

import java.security.SecureRandom;

import java.util.Arrays;


public class Main {

  // perform a linear search on the data

  public static int linearSearch(int data[], int searchKey) {

    // loop through array sequentially

    for (int index = 0; index < data.length; index++)

      if (data[index] == searchKey)

        return index; // return index of integer


    return -1; // integer was not found

  }


  public static void main(String[] args) {

    SecureRandom generator = new SecureRandom();

    /* from 
    时 代 J a v a*/

    int[] data = new int[10]; // create array


    for (int i = 0; i < data.length; i++)

      // populate array

      data[i] = 10 + generator.nextInt(90);


    System.out.printf("%s%n%n", Arrays.toString(data)); // display array


    int searchInt = 123;


    // repeatedly input an integer; -1 terminates the program

    while (searchInt != -1) {

      int position = linearSearch(data, searchInt); // perform search


      if (position == -1) 
展开阅读全文