Comparable+冒泡+选择
Comparable接口(实现比较大小)
用法:
- 实现Comparable接口
- 重写compareTo方法
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Comparable<Student>{
private String username;
private int age;
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
public static void main(String[] args) {
Student s1 = new Student("张三", 13);
Student s2 = new Student("李四", 16);
System.out.println(s1.compareTo(s2));
/*
0 s1=s2
<0 s1<s2
>0 s1>s2
*/
}
}
冒泡排序
排序原理:
- 比较相邻的元素。如果前一个元素比后一个元素大,就交换这两个元素的位置
- 对每一对相邻元素做同样的工作,从开始第一对元素到结尾的最后一对元素。最终最后位置的元素就是最大值
public class Bubble {
/**
* 对数组内的元素进行排序
*
* @param a
*/
public static void sort(Comparable[] a) {
for (int i = a.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (greater(a[j],a[j+1])) {
exch(a,j,j+1);
}
}
}
}
/**
* 判断v是否大于w
*
* @param v
* @param w
* @return
*/
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
/**
* 交换a数组中,索引i和索引j的值
*
* @param a
* @param i
* @param j
*/
private static void exch(Comparable[] a, int i, int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
Integer[] a = {5,4,6,3,2,1};
sort(a);
System.out.println(Arrays.asList(a));
}
}
选择排序
排序原理
- 每次遍历过程中,都假定第一个索引处的元素是最小值,和其他索引的值进行比较,如果单前索引的值大于其他某个位置索引的值,则假定其他某个索引处的值为最小值,最后可以找到最小值所在的索引
- 交换第一个索引处和最小值的索引值
public class Selection {
/**
* 对数组内的元素进行排序
*
* @param a
*/
public static void sort(Comparable[] a) {
for (int i = 0 ; i < a.length - 1; i++) {
int minIndex = i;
for (int j = i+1; j < a.length; j++) {
if(greater(a[minIndex],a[j])){
minIndex = j;
}
}
exch(a,minIndex,i);
}
}
/**
* 判断v是否大于w
*
* @param v
* @param w
* @return
*/
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
/**
* 交换a数组中,索引i和索引j的值
*
* @param a
* @param i
* @param j
*/
private static void exch(Comparable[] a, int i, int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
Integer[] a = {5,4,6,3,1,2,1};
sort(a);
System.out.println(Arrays.asList(a));
}
}