How do you program sorting arrays in Java?
There are two ways to sort an array:
- The sort() method of the Arrays class can be used to sort arrays in Java. This class is a utility class provided by Java for manipulating arrays, and it contains various useful methods. The sort() method sorts the array according to the natural order of its elements, such as ascending order for numbers and dictionary order for strings.
import java.util.Arrays;
public class SortArray {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1};
Arrays.sort(arr); // 对数组进行排序
for (int num : arr) {
System.out.print(num + " ");
}
}
}
The output result is: 1 2 3 5 8
- Custom sorting algorithms can be used to sort arrays based on specific rules, such as sorting by the absolute value of numbers. One example is using the Bubble Sort algorithm to sort an array.
public class SortArray {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1};
bubbleSort(arr); // 使用冒泡排序算法对数组进行排序
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
The output will be: 1 2 3 5 8