一、Comparable和Comparator
比较需要可以比较
- 定义数据类型
public class Employee implements Comparable<Employee> {
private String name;
private int age;
private String salary;
public Employee() {}
public Employee(String name, int age, String salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
// 省略方法
@Override
public int compareTo(Employee o) {
return this.name.compareTo(o.getName());
}
}
- 初始化数据
// Exception in thread "main" java.lang.ClassCastException: com.three.Employee cannot be cast to java.lang.Comparable
// Set<Employee> emplloyees =new TreeSet<>() ;
// emplloyees.add(new Employee());
Employee employee1 = new Employee("张三", 11, "11");
Employee employee2 = new Employee("李四", 12, "11");
Employee employee3 = new Employee("王五", 13, "11");
- 升序
// 升序
// 比较的是值
// TreeSet(Comparator<? super E> var1)
Set<Employee> set = new TreeSet<>((o1, o2) -> o1.getName().compareTo(o2.getName()));
set.add(employee1);
set.add(employee2);
set.add(employee3);
System.out.println(set);
// [Emplloyee [name=张三, age=11, salary=11], Emplloyee [name=李四, age=12, salary=11], Emplloyee [name=王五, age=13, salary=11]]
- 降序
// 降序
// 比较的是键
// TreeMap(Comparator<? super K> var1)
Map<String, Employee> map = new TreeMap<>((o1, o2) -> o2.compareTo(o1));
map.put("a", employee1);
map.put("b", employee2);
map.put("c", employee3);
System.out.println(map);
// {c=Emplloyee [name=王五, age=13, salary=11], b=Emplloyee [name=李四, age=12, salary=11], a=Emplloyee [name=张三, age=11, salary=11]}
二、冒泡算法
- 初始化数据
int[] arr = {8, 30, 2, 50, 15, 100, 11, 25, 5, 10};
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
// 思路
// 8 30 2 50 15 100 11 25 5 10
// 8 2 30 15 50 11 25 5 10 100 第一轮比较:10个数对吧9次
// 2 8 15 30 11 25 5 10 50 100 第二轮比较:10个数对吧8次
- 升序
// 比较几轮 升序
// 减少一次没必要的交换 arr.length - 1
for (int i = 0; i < arr.length - 1; i++) { // 9 8 7 6
// 前后对比
// 这里需要减一 因为arr[j+1];
for (int j = 0; j < arr.length - 1 - i; j++) { // 8 7 6 5
// 交换前后数字
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
- 升序
// 写法二 升序
for (int i = 0; i < arr.length - 1; i++) { // 9 8 7 6
for (int j = 1; j < arr.length - i; j++) { // 8 7 6 5
// 交换前后数字
if (arr[j - 1] > arr[j]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
System.out.println();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}