Array sorting is a common operation in programming. When we have a set of unordered data, sorting can make the data more organized, facilitating subsequent tasks like searching, analysis, or presentation. In Java, the Arrays class in the java.util package provides the sort() method for handling array sorting. Let’s learn how to use Arrays.sort() to implement ascending order sorting and related considerations.
1. Introduction to Arrays.sort()¶
To use Arrays.sort(), you first need to import the java.util.Arrays package:
import java.util.Arrays;
Arrays.sort() sorts arrays in ascending order by default (from smallest to largest).
2. Ascending Sorting of Basic Data Type Arrays¶
For arrays of basic data types (e.g., int, double, char), Arrays.sort() sorts them by numerical value or the natural order of characters (from smallest to largest).
Example: Sorting an int Array¶
import java.util.Arrays;
public class IntArraySort {
public static void main(String[] args) {
// Define an unsorted int array
int[] numbers = {5, 2, 8, 1, 9, 3};
// Sort the array in ascending order
Arrays.sort(numbers);
// Print the sorted array
System.out.println("Sorted int array:");
for (int num : numbers) {
System.out.print(num + " "); // Output: 1 2 3 5 8 9
}
}
}
Key Points:
- sort() modifies the original array in-place (it does not return a new array).
- The sorted array is in ascending order (smallest to largest).
Examples of Other Basic Types¶
doublearray:double[] scores = {85.5, 92.0, 78.3};sorts to[78.3, 85.5, 92.0].chararray:char[] chars = {'c', 'a', 'b'};sorts to['a', 'b', 'c'](by Unicode values).
3. Ascending Sorting of String Arrays¶
For string arrays (reference types), Arrays.sort() sorts by lexicographical order (i.e., character Unicode values).
Example: Sorting a String Array¶
import java.util.Arrays;
public class StringArraySort {
public static void main(String[] args) {
// Define an unsorted string array
String[] fruits = {"banana", "apple", "cherry", "date"};
// Sort the array
Arrays.sort(fruits);
// Print the sorted array
System.out.println("Sorted string array:");
for (String fruit : fruits) {
System.out.print(fruit + " "); // Output: apple banana cherry date
}
}
}
Key Points:
- Strings are sorted lexicographically (like dictionary order). For example, "apple" comes before "banana" because the Unicode value of 'a' is less than 'b'.
4. Important Notes¶
- Import the Arrays Package: Forgetting
import java.util.Arrays;causes a compilation error (“cannot find symbol”). - In-Place Modification:
sort()modifies the original array. For example,[5, 2, 8]becomes[2, 5, 8]. - Consistency of Natural Order:
- Basic types: Sorted by numerical value (e.g.,1 < 2 < 3forint).
- Strings: Sorted by Unicode character order (e.g.,"a" < "b" < "c").
5. Extended: Sorting Custom Object Arrays¶
For arrays of custom objects (e.g., Student), sort() requires elements to implement the Comparable interface or use a Comparator to define sorting rules. For example:
// Assume a Student class with name and score
class Student implements Comparable<Student> {
private String name;
private int score;
// Implement Comparable to sort by score (ascending)
@Override
public int compareTo(Student o) {
return this.score - o.score; // Lower score comes first
}
}
// Usage:
Student[] students = {new Student("Zhang San", 80), new Student("Li Si", 95)};
Arrays.sort(students); // Sorts by score in ascending order
(This is advanced content; beginners may learn it later.)
Summary¶
Arrays.sort() is a fundamental tool for ascending order sorting in Java. By importing java.util.Arrays, you can use it to sort basic data types (numerical/character order) and strings (lexicographical order). Key takeaways:
- In-place modification: The original array is changed.
- Correct package import: Always include import java.util.Arrays;.
- Natural order consistency: Follows numerical or Unicode rules.
This method efficiently handles most simple array sorting requirements.