二分查找的泛型
相比于普通的for循环,二分查找的优势:比较次数少,查找速度快,平均性能
好!
只需要重写排序规则,就可以随意调用二分查找快速查询!
01 Student 类:
package com.GennericBinaryQuery;
public class Student {
private Integer id;
private String name;
private Double score;
public Student(Integer id, String name, Double score) {
super();
this.id = id;
this.name = name;
this.score = score;
}
public Student() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
@Override
public String toString() {
return String.format("Student [id=%s, name=%s, score=%s]", id, name, score);
}
}
02 测试类:
package com.GennericBinaryQuery;
import java.util.Arrays;
import java.util.Comparator;
import com.GennericCompartorSort.Student;
public class Test {
public static void main(String[] args) {
// 01 创建一个学生数组
Student[] stus = { new Student(1750720020, "刘备", 59d),
new Student(1750720017,"曹操", 98.5),
new Student(1750720019, "孙权", 90d),
new Student(1750720018, "司马懿", 95.5)
};
// 02 写排序规则
Comparator<Student> c = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
double temp = o1.getScore() - o2.getScore();
return temp > 0 ? 1 : (temp == 0 ? 0 : -1);
}
};
// 03 二分法查找要先排序(升序排)
Arrays.sort(stus, c);
// 04 创建要查询的对象
Student stu = new Student();
stu.setScore(99.5);
// 04 开始查询
int index = binaryQuery(stus, stu, c);
// System.out.println(Arrays.toString(stus));
for (int i = 0; i < stus.length; i++) {
System.out.println(stus[i]);
}
System.out.println("查找的结果(下标):" + index);
}
public static <T, E> int binaryQuery(T[] t, T Querytarget, Comparator<T> c) {
return binaryQuery(t, Querytarget, 0, t.length - 1, c);
}
public static <T, E> int binaryQuery(T[] t, T querytarget, int start, int end, Comparator<T> c) {
int index = (start + end) / 2;
if(start > end) {
return -1;
}
// int n = c.compare(T a, T b);
// n < 0, 第1个参数小于第2个参数
// n = 0, 第1个参数等于第2个参数
// n > 0, 第1个参数大于第2个参数
int n = c.compare(querytarget, t[index]);
if(n < 0) {
return binaryQuery(t, querytarget, start, index - 1, c);
}else if (n == 0) {
return index;
} else {
return binaryQuery(t, querytarget, index + 1, end, c);
}
}
public static <T, E> int binaryQuery2(T[] t, T querytarget, int start, int end, Comparator<T> c) {
while (start <= end) {
int index = (start + end) / 2;
// int n = c.compare(T a, T b);
// n < 0, 第1个参数小于第2个参数
// n = 0, 第1个参数等于第2个参数
// n > 0, 第1个参数大于第2个参数
int n = c.compare(querytarget, t[index]);
if (n < 0) {
end = index - 1;
} else if (n == 0) {
return index;
} else {
start = index + 1;
}
}
return -1;
}
}
Run: