Java基础查找算法(1)——线性查找(顺序查找)

Java基础查找算法(1)——线性查找(顺序查找)

1.线性查询简述

线性查找,也称顺序查找。查找思路:从数组的一端开始遍历,分别与目标值比较,相等则将下标添加到目标值的下标集合中。

2.代码实现

2.1简洁代码

 private static List<Integer> result = new ArrayList<>();
 public static List<Integer> search(int[] arr, int a) {
        for (int i = 0; i < arr.length; i++) {
            if (a == arr[i]) result.add(i);
        }
        return result;
    }

2.2 工具类

为了方便后面专注于编写查找算法代码的实现,将打印数组和生成随机的测试数组放到了工具类当中:

  • show(int[] arr) 遍历打印数组所有数据
  • getIntData(int testSize) 获取int类型测试数组 大小为testSize
package Utils;

public class ArrUtil {

    /**
     * 遍历输出整个数组
     *
     * @param arr 需要输出的数组
     */
    public static void show(int[] arr) {
        for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " ");
        System.out.println();//换行
    }


    /**
     * 获取随机 整形数据 数组
     *
     * @param testSize 数组大小
     * @return
     */
    public static int[] getIntData(int testSize) {
        int[] a = new int[testSize];
        for (int i = 0; i < testSize; i++)
            a[i] = (int) (Math.random() * testSize);
        return a;
    }
}

2.3 完整代码(含注释与运行实例)

package Algorithm.Search;

import Algorithm.Sort.Template;
import Utils.ArrUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 查找(1)
 * 线性查找(顺序查找)
 */
public class LinearSearch {

    private static List<Integer> result = new ArrayList<>();

    /**
     * 查找
     *
     * @param a   需要查找的数值
     * @param arr 原始的数组
     * @return 返回查找值的下标
     */
    public static List<Integer> search(int[] arr, int a) {
        //遍历整个数组,遇到即返回下标,否则返回-1
        for (int i = 0; i < arr.length; i++) {
            if (a == arr[i]) result.add(i);
        }
        return result;
    }

    public static void main(String[] args) {
        int testSize = 10;
        int[] arr = Template.getIntData(testSize);
        //输出原数组
        ArrUtil.show(arr);
        int a = (int) (Math.random() * testSize);

        System.out.println("查找" + a);

        List<Integer> index = search(arr, a);

        System.out.println("下标" + index);

        //if (index != -1) System.out.println("数组实际元素 arr[" + index + "]=" + arr[index]);

    }
}

3.运行效果

8 29 6 22 26 26 18 10 23 12 14 20 25 28 7 3 1 23 18 10 29 3 8 4 24 27 5 4 16 27 
查找26
下标[4, 5]
发布了67 篇原创文章 · 获赞 32 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42391904/article/details/101306237