参考jdk源码编写的排序算法在对象中的应用
- 实体类
package com.mylearn.pojo;
public class Person implements Comparable<Person>{
private String name;
private Integer salary;
public Person(String name, Integer salary){
this.name = name;
this.salary = salary;
};
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", salary=" + salary +
'}';
}
@Override
public int compareTo(Person o) {
return this.getSalary()-o.getSalary() > 0 ? 1 : this.getSalary()-o.getSalary() == 0 ? 0 : -1;
}
}
- 排序算法的实现(未完)
public class MyCollections{
static void swap(Object[] o,Integer index1,Integer index2){
Object temp = o[index1];
o[index1] = o[index2];
o[index2] = temp;
}
/**
* 冒泡排序
* @param list
* @param c
* @param <T>
*/
public static <T> void bubbleSort(List<T> list, Comparator<? super T> c){
Object[] objects = list.toArray();
Comparator cp = (Comparator)c;
for (int i = 0; i < objects.length; i++) {
for (int j = 0; (j < objects.length-i-1); j++){
if (cp.compare(objects[j],objects[j+1]) >0){
swap(objects,j,j+1);
}
}
}
System.out.println(Arrays.toString(objects));
}
/**
* 快速排序
* @param objArr
* @param begin
* @param end
* @return
*/
public static Object[] quickSort(Object[] objArr, int begin, int end){
int i= begin;
int j = end;
if (begin > end) return new Object[1];
Comparable pivot = (Comparable)objArr[begin];
while (i< j){
while (i<j && (pivot.compareTo(objArr[j]))<= 0){
j--;
}
while (i<j && (pivot.compareTo(objArr[i]))>= 0){
i++;
}
if (i<j){
swap(objArr,i,j);
}
objArr[begin] = objArr[i];
objArr[i] = pivot;
}
quickSort(objArr,begin,i-1);
quickSort(objArr,i+1,end);
return objArr;
}
}
- 测试main方法
public static void main(String[] args) {
Integer[] intArr = {-8,7,5,23,4,-7,0,0 ,7,38,15,36,2,3,1,7,-4,-8,23,57,12,38,67,-8,22};
List<Person> peopleList = Arrays.asList(
new Person("小李", 3500), new Person("小李2", 3300), new Person("小李3", 3600),
new Person("小李4", 3330),new Person("小李5", 3444)
);
//冒泡排序
MyCollections.bubbleSort(Arrays.asList(intArr), (i1,i2)-> i1 - i2);
MyCollections.bubbleSort(peopleList,(p1,p2)-> p1.getSalary() - p2.getSalary());
//快速排序
Object[] objects = MyCollections.quickSort(intArr, 0, intArr.length - 1);
System.out.println(Arrays.toString(objects));
Object[] objects1 = MyCollections.quickSort(peopleList.toArray(), 0, peopleList.size()-1);
System.out.println(Arrays.toString(objects1));
}
总结:
https://blog.csdn.net/he37176427/article/details/97795963 参考:Java 快速排序 关于起始方向的选择问题