Java最大值最小值交换代码
时间: 2023-07-02 14:18:52 浏览: 49
Java中可以使用Math.max()和Math.min()方法来获取最大值和最小值。下面是使用这两个方法进行最值交换的代码示例:
```
int a = 10;
int b = 20;
int max = Math.max(a, b);
int min = Math.min(a, b);
a = min;
b = max;
System.out.println("a = " + a + ", b = " + b);
```
输出结果为:a = 20, b = 10。
相关问题
java数组最大值和最小值交换
要交换Java数组中的最大值和最小值,可以按照以下步骤进行操作:
1. 遍历数组,找到最大值和最小值的索引。
2. 使用临时变量存储最大值的值。
3. 将最小值赋给最大值的位置。
4. 将临时变量中的最大值赋给最小值的位置。
下面是一个示例代码:
```java
public class ArrayMinMaxSwap {
public static void main(String[] args) {
int[] arr = {5, 2, 9, 1, 3};
// 找到最大值和最小值的索引
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;
// 输出交换后的数组
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
运行以上代码,输出结果为:1 2 9 5 3,即最大值和最小值已经成功交换。
交换最大值与最小值 java
以下是Java代码,用于在数组中交换最大值和最小值:
```java
public static void swapMinMax(int[] arr) {
int min = 0, max = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[max]) {
max = i;
}
if (arr[i] < arr[min]) {
min = i;
}
}
int temp = arr[min];
arr[min] = arr[max];
arr[max] = temp;
}
```
这个方法接受一个整数数组作为参数,并使用for循环遍历数组以查找最大值和最小值的索引。然后,它交换这两个值。
相关推荐
![](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)