The Java API's description of the Arrays class is: This class contains various methods used to manipulate arrays (such as sorting and searching).
1. Sort arrays of basic data types
illustrate:
(1) sort() in the Arrays class uses "tuned quick sorting method";
(2) For example, arrays of base data types such as int[], double[], char[], etc., the Arrays class only provides the default ascending order arrangement, and does not provide the corresponding descending order arrangement method.
(3) To sort the arrays of basic types in descending order, you need to convert these arrays into corresponding encapsulated class arrays, such as Integer[], Double[], Character[], etc., to sort these class arrays. (In fact, it is better to sort ascending order first and turn it into the order yourself).
Sort arrays in default ascending order
Function prototype: static void sort(int[] a) Sort the specified int-type array in ascending order.
static void sort(int[] a, int fromIndex, int toIndex) Sort the specified range of an array of int type in ascending numbers.
Code example:
The code copy is as follows:
import java.util.Arrays;
public class ArraysSort_11 {
public static void main(String args[])
{
int[] a={1,4,-1,5,0};
Arrays.sort(a);
//The content of array a[] becomes {-1,0,1,4,5}
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
2. Sort the data of composite data types
Function prototype:
(1) public static<T> void sort(T[] a, Comparator c) Sort the specified object array according to the order generated by the specified comparator.
(2) public static<T> void sort(T[] a, int fromIndex, int toIndex, Comparator c) Sort the specified range of the specified object array according to the order generated by the specified comparator.
Note: These two sorting algorithms are "tuned merge sorting" algorithm.
Code example:
The code copy is as follows:
package aa;
import java.util.Arrays;
import java.util.Comparator;
public class Arraysort {
Point[] arr;
Arraysort(){
arr=new Point[4]; //Define the object array arr and allocate the storage space
for(int i=0;i<4;i++)
arr[i]=new Point();
}
public static void main(String[] args) {
Arraysort sort=new Arraysort();
sort.arr[0].x=2;sort.arr[0].y=1; //Initialize, data in object array
sort.arr[1].x=2;sort.arr[1].y=2;
sort.arr[2].x=1;sort.arr[2].y=2;
sort.arr[3].x=0;sort.arr[3].y=1;
Arrays.sort(sort.arr, new MyComprator()); //Sort with the specified sorter
for(int i=0;i<4;i++) //Output sorting result
System.out.println("("+sort.arr[i].x+","+sort.arr[i].y+")");
}
}
class Point{
int x;
int y;
}
//Comparator, x coordinates are sorted from small to large; when x is the same, they are sorted from small to large according to y
class MyComprator implements Comparator {
public int compare(Object arg0, Object arg1) {
Point t1=(Point)arg0;
Point t2=(Point)arg1;
if(t1.x != t2.x)
return t1.x>t2.x? 1:-1;
else
return t1.y>t2.y? 1:-1;
}
}