3.分析以下需求,并用代码实现:
(1)定义一个int类型的一维数组,内容为{6,2,9,15,1,5,20,7,18}
(2)将数组最大元素与最后一位元素进行交换,最小元素与第一位元素进行交换,并打印数组
提示思路:先查找最大值和最小值出现的索引。
int [] arr = {6,2,9,15,1,5,20,7,18};
int min = arr[0];
int max = arr[0];
for (int i = 0;i < arr.length ;i++ ) {
min = min < arr[i] ? min : arr[i];
max = max > arr[i] ? max : arr[i];
}
System.out.println("max = "+max);
System.out.println("min = "+min);
for (int i = 0; i < arr.length; i++ ) {
if (arr[i] == max) {
int temp1 = arr[i];
arr[i] = arr[arr.length - 1];
arr[arr.length - 1] = temp1;
}
if (arr[i] == min) {
int temp2 = arr[i];
arr[i] = arr[0];
arr[0] = temp2;
}
}
for (int i = 0; i < arr.length; i++ ){
System.out.print(" " + arr[i]);
}
|
|