前言
排序是非常常见的一种需求,如查询订单,按照订单的日期进行排序;如查询商品,按照商品的价格进行排序等
在java的开发工具包jdk中,已经提供了很多数据结构与算法的实现,比如List,Set,Map等,都
是以API的方式提供,这种方式的好处在于一次编写,多处使用。借鉴jdk的方式把算法封装到某个类,
所以在编写java代码之前,先进行API的设计,再对API进行实现
一. Comparable(在类的设计中使用)
1.1 Comparable排序接口
若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或 Arrays.sort进行自动排序。实现此接口的对象可以用作有序映射中的键或有序集合中的集合,无需指 定比较器
1.2 范例
自定义实体类:
public class Student implements Comparable<Student> {
private String username;
private int age;
public Student(String username, int age) {
this.username = username;
this.age = age;
}
public Student() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" + "username='" + username + '\'' + ", age=" + age + '}';
}//定义比较规则
@Override
public int compareTo(Student o) {
return this.getAge() - o.getAge();
}
}
Collections.sort排序
public class Test {
public static void main(String[] args) {
Student mike = new Student("mike", 39);
Student cz = new Student("cz", 18);
Student lily = new Student("lily", 24);
Student tom = new Student("tom", 15);
ArrayList<Student> students = new ArrayList<>();
students.add(mike);
students.add(cz);
students.add(lily);
students.add(tom);
Collections.sort(students);
for (Student s : students) {
System.out.println(s);
}
}
}
结果输出:

1.3 Collections.sort源码分析:

查看 ArrayList类中sort方法:

查看Arrays类中sort方法




排序核心源码如下:基于binary insertion sort
private static void binarySort(Object[] a, int lo, int hi, int start) {
assert lo <= start && start <= hi;
if (start == lo)
start++;
for ( ; start < hi; start++) {
Comparable pivot = (Comparable) a[start];
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left).
* pivot < all in [right, start).
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (pivot.compareTo(a[mid]) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
switch (n) {
case 2: a[left + 2] = a[left + 1];
case 1: a[left + 1] = a[left];
break;
default: System.arraycopy(a, left, a, left + 1, n);
}
a[left] = pivot;
}
}
二. Comparator(用于类设计已经完成)
2.1 Comparator排序接口
Comparator接口用于类设计已经完成,仍然需要排序;
2.2 范例
自定义实体类:
public class Student {
private String username;
private int age;
public Student(String username, int age) {
this.username = username;
this.age = age;
}
public Student() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" + "username='" + username + '\'' + ", age=" + age + '}';
}//定义比较规则
}
Collections.sort排序:
public class Test {
public static void main(String[] args) {
Student mike = new Student("mike", 39);
Student cz = new Student("cz", 18);
Student lily = new Student("lily", 24);
Student tom = new Student("tom", 15);
ArrayList<Student> students = new ArrayList<>();
students.add(mike);
students.add(cz);
students.add(lily);
students.add(tom);
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if(o1.getAge()>o2.getAge()){
return 1;
}
return -1;
}
});
for (Student s : students) {
System.out.println(s);
}
}
}
结果输出:

三. 冒泡排序
3.1 排序原理
1. 比较相邻的元素。如果前一个元素比后一个元素大,就交换这两个元素的位置。
2. 对每一对相邻元素做同样的工作,从开始第一对元素到结尾的最后一对元素。最终最后位置的元素就是最大值

3.2 冒泡排序api设计和代码实现
| 类名 | Bubble |
|---|---|
| 构造方法 | Bubble():创建Bubble对象 |
成员方法:
public static void sort(Comparable[] a):对数组内的元素进行排序 ;
private static boolean greater(Comparable v,Comparable w):判断v是否大于w;
private static void exch(Comparable[] a,int i,int j):交换a数组中,索引i和索引j处的值
public class Bubble {
public static void sort(Comparable[] a) {
for (int i = a.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
//比较索引j和j+1
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;
}
/**
* 交换元素
*
* @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;
}
}
3.3 测试
public static void main(String[] args) {
Integer[] a = new Integer[100000];
for(int i=0;i<100000;i++){
int element = new Random().nextInt(1000);
a[i]=element;
}
long start = System.currentTimeMillis();
Shell.sort(a);
long end = System.currentTimeMillis();
System.out.println(Arrays.toString(a));
System.out.println("排序用时:"+(end-start));
}
3.4 冒泡排序的时间复杂度分析
在最坏情况下,也就是假如要排序的元素为逆序,那么:
元素比较的次数为:
(N-1)+(N-2)+(N-3)+...+2+1=((N-1)+1)*(N-1)/2=N^2/2-N/2;
元素交换的次数为:
(N-1)+(N-2)+(N-3)+...+2+1=((N-1)+1)*(N-1)/2=N^2/2-N/2;
总执行次数为:
(N^2/2-N/2)+(N^2/2-N/2)=N^2-N;
按照大O推导法则,保留函数中的最高阶项那么最终冒泡排序的时间复杂度为O(N^2)
3.5 冒泡排序优化
在上面排序原理图中,第三趟结束,实际已经有序,因此可设置一个标志位,记录上一次排序是否有交换,没有交换就可以提前结束
public class Bubble {
public static void sort(Comparable[] a) {
boolean flag = true; //添加标志位
for (int i = a.length - 1; i > 0 && flag; i--) {
flag = false;
for (int j = 0; j < i; j++) {
//比较索引j和j+1
if (greater(a[j], a[j + 1])) {
exch(a, j, j + 1);
flag = true;
}
}
}
}
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
四. 选择排序
4.1 排序原理
1.每一次遍历的过程中,都假定第一个索引处的元素是最小值,和其他索引处的值依次进行比较,如果当前索引处的值大于其他某个索引处的值,则假定其他某个索引出的值为最小值,最后可以找到最小值所在的索引
2.交换第一个索引处和最小值所在的索引处的值

4.2 选择排序api设计和代码实现
| 类名 | Selection |
|---|---|
| 构造方法 | Selection():创建Bubble对象 |
成员方法:
public static void sort(Comparable[] a):对数组内的元素进行排序 ;
private static boolean greater(Comparable v,Comparable w):判断v是否大于w;
private static void exch(Comparable[] a,int i,int j):交换a数组中,索引i和索引j处的值
在内循环中标注每次排序中最小值的索引,避免
public class Selection {
public static void sort(Comparable[] a) {
for (int i = 0; i < a.length - 1; i++) {
//假设i为每次排序中最小值的索引
int minIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (greater(a[minIndex], a[j])) {
//更换最小值所在的索引
minIndex = j;
}
}
//交换i索引处和minIndex索引处的值
exch(a, i, minIndex);
}
}
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
4.3 测试
public static void main(String[] args) {
Integer[] a = new Integer[100000];
for(int i=0;i<100000;i++){
int element = new Random().nextInt(1000);
a[i]=element;
}
long start = System.currentTimeMillis();
Selection.sort(a);
long end = System.currentTimeMillis();
System.out.println(Arrays.toString(a));
System.out.println("排序用时:"+(end-start));
}
4.4 选择排序的时间复杂度分析
选择排序使用了双层for循环,其中外层循环完成数据交换,内层循环完成数据比较,分别统计数据
交换次数和数据比较次数:
数据比较次数:
(N-1)+(N-2)+(N-3)+...+2+1=((N-1)+1)*(N-1)/2=N^2/2-N/2;
数据交换次数:
N-1
时间复杂度:N^2/2-N/2+(N-1)=N^2/2+N/2-1;
根据大O推导法则,保留最高阶项,去除常数因子,时间复杂度为O(N^2);
4.5 选择排序优化
可每次遍历剩余元素的时候,找出最小值和最大值,并排定最小值和最大值,这样遍历的次数会减少一半。
public class Selection {
public static void sort(Comparable[] a) {
for (int left = 0, right = a.length - 1; left < right; left++, right--) {
int min = left;
int max = right;
for (int index = left; index <= right; index++) {
if (greater(a[min], a[index])) {
min = index;
}
if (greater(a[index], a[max])) {
max = index;
}
}
exch(a, left, min);
//此处是先排最小值的位置,所以得考虑最大值(arr[max])在最小位置(left)的情况。
if (left == max) {
max = min;
}
exch(a, right, max);
}
}
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
五. 插入排序
5.1 排序原理
1.把所有的元素分为两组,已经排序的和未排序的;
2.找到未排序的组中的第一个元素,向已经排序的组中进行插入;
3.倒叙遍历已经排序的元素,依次和待插入的元素进行比较,直到找到一个元素小于等于待插入元素,那么就把待插入元素放到这个位置,其他的元素向后移动一位;

5.2 插入排序api设计和代码实现
| 类名 | Insertion |
|---|---|
| 构造方法 | Insertion():创建Insertion对象 |
成员方法:
public static void sort(Comparable[] a):对数组内的元素进行排序 ;
private static boolean greater(Comparable v,Comparable w):判断v是否大于w;
private static void exch(Comparable[] a,int i,int j):交换a数组中,索引i和索引j处的值
public class Insertion {
public static void sort(Comparable[] a) {
for (int i = 1; i < a.length; i++) {
for (int j = i; j > 0; j--) {
if (greater(a[j - 1], a[j])) {
exch(a, j - 1, j);
} else {
break;
}
}
}
}
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
}
5.3 测试
public static void main(String[] args) {
Integer[] a = new Integer[100000];
for(int i=0;i<100000;i++){
int element = new Random().nextInt(1000);
a[i]=element;
}
long start = System.currentTimeMillis();
Insertion.sort(a);
long end = System.currentTimeMillis();
System.out.println(Arrays.toString(a));
System.out.println("排序用时:"+(end-start));
}
5.4 插入排序的时间复杂度分析
最坏情况比较的次数为:
(N-1)+(N-2)+(N-3)+...+2+1=((N-1)+1)*(N-1)/2=N^2/2-N/2;
交换的次数为:
(N-1)+(N-2)+(N-3)+...+2+1=((N-1)+1)*(N-1)/2=N^2/2-N/2;
总执行次数为:
(N^2/2-N/2)+(N^2/2-N/2)=N^2-N;
按照大O推导法则,保留函数中的最高阶项那么最终插入排序的时间复杂度为O(N^2).
5.5 插入排序优化
Collections.sort中使用二分搜索插入排序,可参看上面的源码
本文详细介绍了Java中的Comparable接口和Comparator接口在类设计和已完成后如何实现排序,以及冒泡排序、选择排序和插入排序的原理、API设计、代码实现、时间复杂度分析和优化方法。通过实例展示了如何使用Collections.sort方法,以及自定义排序逻辑。此外,还探讨了这些排序算法的时间复杂度,为实际编程提供了参考。
855

被折叠的 条评论
为什么被折叠?



