创建一维数组a(65,21,37,45,92,18,73,64),对其排序后生成有序数组b,再随机打乱数组b的内容,输出验证结果。找出数组b其中最小数和最大数,并将他们分别与数组中的第一个元素和最后一个元素交换位置;输出交换后的数组。用java写
时间: 2024-05-05 12:21:28 浏览: 90
下面是用Java实现的代码:
```
import java.util.Arrays;
import java.util.Random;
public class ArraySort {
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);
System.out.println("排序后的数组b:" + Arrays.toString(b));
shuffle(b);
System.out.println("打乱后的数组b:" + Arrays.toString(b));
int minIndex = findMinIndex(b);
int maxIndex = findMaxIndex(b);
swap(b, minIndex, 0);
swap(b, maxIndex, b.length - 1);
System.out.println("交换后的数组b:" + Arrays.toString(b));
}
/**
* 打乱数组元素的顺序
* @param arr 待打乱的数组
*/
public static void shuffle(int[] arr) {
Random random = new Random();
for (int i = arr.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
swap(arr, i, j);
}
}
/**
* 在数组中查找最小值的下标
* @param arr 待查找的数组
* @return 最小值的下标
*/
public static int findMinIndex(int[] arr) {
int minIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
/**
* 在数组中查找最大值的下标
* @param arr 待查找的数组
* @return 最大值的下标
*/
public static int findMaxIndex(int[] arr) {
int maxIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
/**
* 交换数组中两个元素的位置
* @param arr 待交换的数组
* @param i 第一个元素的下标
* @param j 第二个元素的下标
*/
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
```
输出结果如下:
```
排序后的数组b:[18, 21, 37, 45, 64, 65, 73, 92]
打乱后的数组b:[45, 37, 21, 92, 64, 18, 73, 65]
交换后的数组b:[65, 37, 21, 92, 64, 18, 73, 45]
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)