数据结构和算法-线性查找法和测试算法性能

文章目录

  • 线性查找法实现
  • 测试算法性能

线性查找法实现

public class LinearSearch {

    private LinearSearch(){}

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

    public static void main(String[] args){

        Integer[] data = {24, 18, 12, 9, 16, 66, 32, 4};

        int res = LinearSearch.search(data, 16);
        System.out.println(res);

        int res2 = LinearSearch.search(data, 666);
        System.out.println(res2);

        Student[] students = {new Student("A"),
                              new Student("B"),
                              new Student("C")};
        Student c = new Student("C");
        int res3 = LinearSearch.search(students, c);
        System.out.println(res3);
    }
}

对于对象的比较,我们需要自己实现equals方法

public class Student {

    private String name;

    public Student(String name) {
        this.name = name;
    }

    @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.name);
    }
}

打印结果如下:

4
-1
2

测试算法性能

定义一个数组生成器

public class ArrayGenerator {

    private ArrayGenerator(){}

    public static Integer[] generateOrderedArray(int n){

        Integer[] arr = new Integer[n];
        for(int i = 0; i < n; i ++)
            arr[i] = i;
        return arr;
    }
}

测试“线性查找法”算法性能

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

    public static void main(String[] args){

//        int n = 10000;
//        Integer[] data = ArrayGenerator.generateOrderedArray(n);
//
//        long start = System.currentTimeMillis();
//        for (int k = 0; k < 100; k++)
//            LinearSearch.search(data, n);
//        long time = System.currentTimeMillis() - start;
//        System.out.println("n = " + n + " , 100 runs : " + time + "ms");

        int[] dataSize = {1000000, 10000000};
        for(int n: dataSize) {
            Integer[] data = ArrayGenerator.generateOrderedArray(n);

            long startTime = System.nanoTime();
            for (int k = 0; k < 100; k++)
                LinearSearch.search(data, n);
            long endTime = System.nanoTime();

            double time = (endTime - startTime) / 1000000000.0;
            System.out.println("n = " + n + ", 100 runs : " + time + "s");
        }
    }
}

在这里插入图片描述
分别生成0到1000000 和 0到10000000的两个数组,各循环100查看各自运行时间,大致上呈线性关系。

你可能感兴趣的:(#,玩数据结构和算法,数据结构,算法,线性查找法,测试性能)