1.1 Comparable接口介绍
//学生类
public class Student implements Comparable<Student>{
private String username;
private int age;
...
@Override
public int compareTo(Student o) {
return this.getAge()-o.getAge();
}
}
//测试类
public static void main( String[] args )
{
Student student = new Student("qqq", 18);
Student student1 = new Student("ccc", 20);
Comparable max = getMax(student,student1);
System.out.println(max);
}
public static Comparable getMax(Comparable c1,Comparable c2){
int result = c1.compareTo(c2);
if (result<=0){
return c2;
}else {
return c1;
}
}
1.2 冒泡排序
public class Bubble {
//数组排序
public static void sort(Comparable[] a){
for (int i =a.length-1;i>0;i--){ //第i轮比较比较n-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,返回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;
}
}
//运行
public class App
{
public static void main( String[] args )
{
//int arr[] = {4,5,6,3,2,1}; //int为基本数据类型,没有实现Comparator接口,不能使用
Integer arr[] = {4,5,6,3,2,1};//Integer实现Comparator接口
Bubble.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
输出:
冒泡排序的时间复杂度分析
1.3 选择排序
public class Selection {
public static void sort(Comparable[] a){
for (int i=0;i<=a.length-2;i++){ //每轮参与排序的元素个数。剩余两个元素时直接比大小选择
//定义变量存储最小值,默认为参与排序第一个元素的位置
int minindex = i;
for (int j=i+1;j<a.length;j++){
//比较最小索引minindex处的值和j处的值
if (greater(a[minindex],a[j])){ //如果minindex处的值大于j的值,则mindex位置改为j的位置
minindex = j;
}
}
exch(a,minindex,i);
}
}
//比较大小,v>w,返回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;
}
}
//运行
public class App
{
public static void main( String[] args )
{
//int arr[] = {4,5,6,3,2,1}; //int为基本数据类型,没有实现Comparator接口,不能使用
Integer arr[] = {4,5,6,3,2,1};//Integer实现Comparator接口
Selection.sort(arr);
System.out.println(Arrays.toString(arr));
}
public static Comparable getMax(Comparable c1,Comparable c2){
int result = c1.compareTo(c2);
if (result<=0){
return c2;
}else {
return c1;
}
}
}
选择排序的时间复杂度分析:
选择排序使用了双层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);
1.4 插入排序
流程图
代码实现
public class Insertion {
public static void sort(Comparable[] a){
for (int i =1;i<a.length;i++){ //初始化时把a[0]当做已排序数组的值,所以从1开始
for (int j =i;j>0;j--){ //从第j=i个数开始一次与前一个值比较,如果a[j-1]>[j],则交换,否则停止,进行i++1的下一次循环
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 temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
插入排序的时间复杂度分析: