编写Java函数,将数组中的最大值和最小值交换
发布时间:2023-06-30 13:01:48
以下是一个简单的 Java 函数,用于将数组中的最大值和最小值交换:
public class SwapMaxMin {
public static void swapMaxMin(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
int maxIndex = 0; // 最大值的索引
int minIndex = 0; // 最小值的索引
// 查找最大值和最小值的索引
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
// 交换最大值和最小值
int temp = arr[maxIndex];
arr[maxIndex] = arr[minIndex];
arr[minIndex] = temp;
}
public static void main(String[] args) {
int[] arr = {5, 3, 9, 1, 7};
System.out.println("原始数组: ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
swapMaxMin(arr);
System.out.println("交换后的数组: ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}
运行以上代码,输出为:
原始数组: 5 3 9 1 7 交换后的数组: 5 3 1 9 7
上述代码中,swapMaxMin 函数接受一个整数数组作为参数。它首先遍历数组,找到最大值和最小值的索引,然后交换这两个元素。最后,通过在 main 函数中调用 swapMaxMin 函数来测试代码。
