线性查找发-笔记

该博客展示了如何使用线性查找法在整数数组和学生对象数组中搜索目标元素。线性搜索算法在Java中实现,通过遍历数组来查找目标,如果找到则返回其索引,否则返回-1。示例中,算法成功找到了54和'张三'的学生对象,并在找不到777时返回了-1。
摘要由CSDN通过智能技术生成
package 数据结构.线性查找法;

public class LinearSearch {

    private LinearSearch() {
    }

    public static <T> int search(T[] data, T target) {
        for (int i = 0; i < data.length; i++) {
            if (target.equals(data[i]))
                return i;
        }
        return -1;
    }


    public static void main(String[] args) {
        Integer[] data = {112, 33, 55, 54, 12, 59, 74};
        int a = LinearSearch.search(data, 54);
        System.out.println(a);
        int b = LinearSearch.search(data, 777);
        System.out.println(b);
        System.out.println("-----------------------------------");

        Student[] students = {new Student("张三", 18, '男'),
                new Student("李四", 18, '女'),
                new Student("王五", 18, '男'),
                new Student("喜喜", 18, '男')};
        int c = LinearSearch.search(students, new Student("张三", 18, '男'));
        System.out.println(c);
    }
}

package 数据结构.线性查找法;

public class Student {
    private String name;
    private int age;
    private char sex;

    public Student(String name, int age, char sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public boolean equals(Object student) {
        if (this == student)
            return true;
        if (student == null)
            return false;
        if (this.getClass() != student.getClass())
            return false;
        Student another = (Student) student;
        return this.name.equals(another.getName()) && this.age == another.getAge() && this.sex == another.getSex();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值