现在已知数组int[] arr = {12,34,465,3,45};
将最大值和最小值的位置进行交换
/*
* 现在已知数组int[] arr = {12,34,465,3,45};
* 将最大值和最小值的位置进行交换
*/
public class Test {
public static void main(String[] args) {
int[] arr = {12,34,456,3,45};
System.out.print("arr[]:");
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
//max,min
int maxIndex = 0;
int minIndex = 0;
for(int i = 1; i<arr.length; i++) {
if(arr[maxIndex] < arr[i]) {
maxIndex = i;
}
if(arr[minIndex] > arr[i]) {
minIndex = i;
}
}
System.out.println("maxIndex:"+maxIndex+" "+"minIndex:"+minIndex);
int a = arr[maxIndex];
arr[maxIndex] = arr[minIndex];
arr[minIndex] = a;
//
System.out.print("交换后arr[]:");
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
}
arr[]:12 34 456 3 45
maxIndex:2 minIndex:3
交换后arr[]:12 34 3 456 45