Java程序对数组元素进行降序排序
Java程序对数组元素进行降序排序是指将给定的数组元素从大到小排列。例如,输入数组{2, 6, 23, 98, 24, 35, 78},输出结果为[98, 78, 35, 24, 23, 6, 2]。在Java中,存在多种方法来对给定数组进行降序排序。 1.使用Collections.reverseOrder()方法可以通过将数组和Collections.reverseOrder()作为参数传递给Arrays.sort(),来对数组元素进行降序排序。需要注意的是,当按降序排序时,Arrays.sort()不接受原始数据类型的数组。例如: ```java import java.util.*; class GFG { public static void main(String[] args) { // Initializing the array Integer array[] = { 1, 2, 3, 4, 5 }; // Sorting the array in descending order Arrays.sort(array, Collections.reverseOrder()); // Printing the elements System.out.println(Arrays.toString(array)); } } ```输出结果为[5, 4, 3, 2, 1],时间复杂度为O(N log N)。 2.使用排序和反转对给定数组进行排序可以先对数组进行升序排序,然后反转已排序的数组。例如: ```java import java.util.*; class GFG { public static void main(String[] args) { // Initializing the array int array[] = { 1, 2, 3, 4, 5, 6 }; // Sorting the array in ascending order Arrays.sort(array); // Reversing the array reverse(array); // Printing the elements System.out.println(Arrays.toString(array)); } public static void reverse(int[] array) { // Length of the array int n = array.length; // Swapping the first half elements with last half elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily int temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } } ```输出结果为[6, 5, 4, 3, 2, 1],时间复杂度为O(N^2)。在Java 14之前,Arrays.sort(int[])使用双枢轴快速排序,最坏情况复杂度为O(N^2)。从Java 14开始,Arrays.sort(int[])使用introsort算法,时间复杂度为O(N log N)。对数组元素进行降序排序可以通过使用Collections.reverseOrder()方法或排序和反转来实现。不同的方法具有不同的时间复杂度,可以根据实际情况选择合适的方法。
下载地址
用户评论