arr.sort(() => Math.random() - 0.5)这句代码表示什么意思
时间: 2024-03-18 11:45:43 浏览: 24
这行代码是用来打乱数组 `arr` 中元素的顺序。它利用了 `Array.sort()` 方法的排序功能,但是排序的规则是通过一个比较函数 `() => Math.random() - 0.5` 来实现的。这个函数每次比较两个元素时,都会返回一个介于 -0.5 到 0.5 之间的随机数,这样就实现了随机排序的效果。
相关问题
编写sort()方法对一维数组进行排序,在主方法中调用Math.random()产生20个0-100间的整数,然后调用sort()对产生的整数按照升序排列,并对排序前后的数组按照每行5个数的方式输出
```java
public class SortArray {
public static void main(String[] args) {
int[] arr = new int[20];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 101);
}
System.out.println("排序前:");
printArray(arr);
sort(arr);
System.out.println("排序后:");
printArray(arr);
}
public static void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
if ((i + 1) % 5 == 0) {
System.out.println();
}
}
System.out.println();
}
}
```
输出结果:
```
排序前:
87 11 38 42 31
98 54 85 18 79
44 66 68 100 77
60 22 51 63 9
排序后:
9 11 18 22 31
38 42 44 51 54
60 63 66 68 77
79 85 87 98 100
```
Java编写sort()方法对一维数组进行排序,在主方法中调用Math.random()产生20个0-100间的整数,然后调用sort()对产生的整数按照升序排列,并对排序前后的数组按照每行5个数的方式输出。
下面是Java代码实现:
```java
import java.util.Arrays;
public class SortDemo {
public static void main(String[] args) {
int[] arr = new int[20];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 101);
}
System.out.println("排序前:");
printArray(arr);
sort(arr);
System.out.println("排序后:");
printArray(arr);
}
public static void sort(int[] arr) {
Arrays.sort(arr);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
if ((i + 1) % 5 == 0) {
System.out.println();
}
}
System.out.println();
}
}
```
实现方法比较简单,我们使用Java内置的Arrays.sort()方法对数组进行排序即可。然后编写一个printArray()方法来按照每行5个数的方式输出数组。最后在主方法中调用sort()和printArray()方法即可完成题目要求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)