Arrays.sort(arr);
时间: 2023-11-18 14:37:20 浏览: 13
This code sorts an array in ascending order. The method used is the built-in sort method of the Arrays class in Java. The parameter passed to the sort method is the array to be sorted. After the method is executed, the array will be sorted in ascending order.
相关问题
arrays.sort
`Arrays.sort()` 是 Java 中用于对数组进行排序的方法。它可以对任何类型的数组进行排序,包括基本类型和对象类型。排序时可以使用默认的排序顺序,也可以自定义排序顺序。默认情况下,它使用快速排序算法进行排序。
下面是一个使用 `Arrays.sort()` 方法对整数数组进行排序的示例:
```java
int[] arr = {5, 3, 8, 2, 7};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [2, 3, 5, 7, 8]
```
在上面的示例中,我们首先创建了一个整数数组 `arr`,然后使用 `Arrays.sort()` 方法对其进行排序。最后,我们使用 `Arrays.toString()` 方法将排序后的数组转换为字符串并打印出来。
需要注意的是,`Arrays.sort()` 方法会改变原始数组的顺序,如果不想改变原始数组的顺序,可以先将原始数组复制一份再进行排序。
Arrays.sort
Arrays.sort is a built-in method in Java that is used to sort arrays of primitive data types and objects. It sorts the elements of an array in ascending order by default, but can also sort in descending order if a custom comparator is provided.
Syntax:
There are two overloaded versions of the sort() method:
1. For sorting arrays of primitive data types:
public static void sort(type[] arr)
2. For sorting arrays of objects:
public static void sort(Object[] arr)
Examples:
1. Sorting an array of integers in ascending order:
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // prints [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
2. Sorting an array of strings in descending order:
String[] arr = {"apple", "banana", "cherry", "date"};
Arrays.sort(arr, Collections.reverseOrder());
System.out.println(Arrays.toString(arr)); // prints [date, cherry, banana, apple]
Note: The reverseOrder() method is used to create a comparator that sorts elements in reverse order.