一、排序
1、比较器Comparable
Java中的比较器(排序) - 情陌人灬已不在 - 博客园 (cnblogs.com)
Comparable和Comparator接口都是为了对类进行比较,众所周知,诸如Integer,double等基本数据类型,java可以对他们进行比较,而对于类的比较,需要人工定义比较用到的字段比较逻辑。可以把Comparable理解为内部比较器,而Comparator是外部比较器。
实体类student:
public class Student implements Comparable {
private String name;
private int age;
//有参、无参、get、set、tostring
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
}
测试类:
public class TestCompare {
public static void main(String[] args) {
Student s1 = new Student("马云", 40);
Student s2 = new Student("马化腾", 41);
Comparable max = getMax(s1, s2);
System.out.println(max);
}
public static Comparable getMax(Comparable c1, Comparable c2){
int res=c1.compareTo(c2);
if (res>=0){
return c1;
}else {
return c2;
}
}
}
2、冒泡排序
冒泡排序优缺点
- 优点:比较简单,空间复杂度较低,是稳定的
- 缺点:时间复杂度太高,效率较低
java代码:
/*
冒泡排序算法:由小到大 分为三个方法较之前更加 封装解耦
最坏时间复杂度:逆序情况下O(n^2)
适用场景:元素较少的情况下可选择适用
优点:安全稳定排序,比较两个相同的数据时顺序不变
* */
public class BubbleSort {
/*
* 对数组a中的元素排序 Integer 类型 implements Comparable,因此可以采用比较器
* */
public static void bubbleSort(Integer[] a){
for (int i=0;i0;
}
}
测试类:
public class BubbleSortTest {
public static void main(String[] args) {
Integer[] arr= new Integer[]{3, 5, 1, 4, 2};
bubbleSort(arr); //给数组排序
System.out.println(Arrays.toString(arr));
}
}
3、选择排序
java代码:
/*
* 选择排序算法:升序 分为三个方法较之前更加 封装解耦
时间复杂度:O(n^2)
适用场景:元素较少的情况下可选择适用
优点:不稳定排序,比较两个相同的数据时顺序可能发生改变
* */
public class SelectSort {
public static void Sort(Integer[] arr){
//最小元素下标
int minIndex;
for (int i=0;i0;
}
}
测试类:
public class SelectTest {
public static void main(String[] args) {
Integer[] arr=new Integer[]{4,3,5,6,1,2};
Sort(arr);
System.out.println(Arrays.toString(arr));
}
}
选择与冒泡比较:
{{uploading-image-136746.png(uploading...)}}