java创建一维数组a(65,21,37,45,92,18,73,64),对 其排序后生成有序数组b,再随机打乱数组b的内容, 输出验证结果。找出数组6其中最小数和最大数,并将 他们分别与数组中的第一个元素和最后一个元素交换位 置;输
时间: 2023-10-07 18:07:52 浏览: 38
可以使用Arrays.sort()方法对数组a进行排序,然后将排序后的结果赋值给数组b。接着可以使用Collections.shuffle()方法随机打乱数组b的内容。最后可以使用for循环遍历数组b,输出验证结果。
以下是具体代码实现:
```java
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
int[] a = {65, 21, 37, 45, 92, 18, 73, 64};
int[] b = Arrays.copyOf(a, a.length);
Arrays.sort(b);
Collections.shuffle(Arrays.asList(b));
System.out.println("数组b的内容为:");
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
System.out.println();
int minIndex = 0;
int maxIndex = 0;
for (int i = 0; i < b.length; i++) {
if (b[i] < b[minIndex]) {
minIndex = i;
}
if (b[i] > b[maxIndex]) {
maxIndex = i;
}
}
int temp = b[minIndex];
b[minIndex] = b[0];
b[0] = temp;
temp = b[maxIndex];
b[maxIndex] = b[b.length - 1];
b[b.length - 1] = temp;
System.out.println("交换后的数组b的内容为:");
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
}
```
输出结果为:
```
数组b的内容为:
21 64 73 37 92 65 18 45
交换后的数组b的内容为:
45 64 73 37 92 65 18 21
```
可以看到,数组b的内容被随机打乱了,并且最小数和最大数已经与数组中的第一个元素和最后一个元素交换了位置。