Java中Arrays.sort()函数,常用于对数组进行快速排序,原理就是基于快速排序的算法思想
快速排序
快速排序使用的是分治思想,将原问题分成若干个子问题进行递归解决。选择一个元素作为轴(pivot),通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比轴元素小,另外一部分的所有数据都比轴元素大,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
基础知识点:
常见几种用法
案例1:基于数组元素绝对值大小进行排序
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int A[]={1,3,-9,10,-8,-100};
Integer[] B = new Integer[A.length];
for (int i = 0; i < A.length; ++i)
B[i] = A[i];
Arrays.sort(B, Comparator.comparingInt(Math::abs));
for(int b:B)
System.out.println(b);
}
}
案例2:基于二维数组的第一列元素大小排序
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String strs[]={"eat", "tea", "tan", "ate", "nat", "bat"};
for(int i=0;i<strs.length;i++)
{
char cset[]=strs[i].toCharArray();
Arrays.sort(cset);
strT[i]=new String[]{String.valueOf(cset), String.valueOf(i)};
}
Arrays.sort(strT, new Comparator<String[]>() {
@Override
public int compare(String[] o1, String[] o2) {
return o1[0].compareTo(o2[0]);
}
});
}
}
案例3:对类对象进行排序
import java.util.Arrays;
class Student
{
public String name;
public int number;
public int score;
public int age;
public Student(String name,int number,int score,int age)
{
this.name = name;
this.number = number;
this.score = score;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Student[] persons = new Student[5];
persons[0] =new Student("tom",1,88,45);
persons[1] =new Student("jack",6,80,12);
persons[2] =new Student("bill",4,68,21);
persons[3] =new Student("kandy",2,98,34);
persons[4] =new Student("lily",5,94,20);
Student[] persons = new Student[5];
persons[0] =new Student("tom",1,88,45);
persons[1] =new Student("jack",6,80,12);
persons[2] =new Student("bill",4,68,21);
persons[3] =new Student("kandy",2,98,34);
persons[4] =new Student("lily",5,94,20);
//按照成绩大小升序排序
Arrays.sort(persons, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2)
{
return o1.getScore()-o2.getScore();
}
});
for(int i=0;i<persons.length;i++)
System.out.println(persons[i].getName()+" "+persons[i].getNumber()+" "
+persons[i].getScore()+" "+persons[i].getAge());
}
}