Sort an array in Java
To sort an array in Java, you can use the Arrays.sort()
method of the java.util.Arrays
class. This method sorts the elements of the array in ascending order according to their natural ordering.
Here's an example of how to use the sort()
method to sort an array of integers:
int[] numbers = {3, 2, 1};
Arrays.sort(numbers);
This will sort the array numbers
in ascending order, so it will contain the elements 1, 2, 3
.
You can also use the sort()
method to sort an array of objects, as long as the objects implement the Comparable
interface and define a natural ordering. For example:
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return this.age - o.age;
}
}
In this example, the Person
class implements the Comparable
interface and defines a natural ordering based on the age of the person. You can then use the sort()
method to sort an array of Person
objects:
Person[] people = {new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 20)};
Arrays.sort(people);
This will sort the array people
in ascending order based on the age of the person.
If you want to sort the array in descending order, you can use the sort()
method of the java.util.Collections
class and pass a comparator that compares the elements in reverse order. Here's an example:
import java.util.Collections;
int[] numbers = {3, 2, 1};
Collections.sort(numbers, Collections.reverseOrder());
This will sort the array numbers
in descending order, so it will contain the elements 3, 2, 1
.
Note that the sort()
method uses a stable sort, which means that the relative order of equal elements is preserved. If you want to use a different sorting algorithm, you can use the sort()
method of the java.util.Arrays
class and pass a comparator as an argument.