In: Computer Science
Write a method public static void minMax(int[] arr) that takes an array of unique ints of length at least two as an argument, and swaps the smallest value of the array into the 0th position and swaps the largest value of the array into the last position.
For example, if int[] a = {4, 3, 2, 6, 1, 5}, the method call minMax(a) should modify the array so that it is {1, 3, 2, 5, 4, 6}.
The method should make only one pass through the array.
The method should not return a value. Instead, it should modify the array in place.
public static void minMax(int[] arr) { int minIndex = 0, maxIndex = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] < arr[minIndex]) minIndex = i; if (arr[i] > arr[maxIndex]) maxIndex = i; } int temp = arr[0]; arr[0] = arr[minIndex]; arr[minIndex] = temp; temp = arr[arr.length - 1]; arr[arr.length - 1] = arr[maxIndex]; arr[maxIndex] = temp; }
import java.util.Arrays; public class MinMaxTest { public static void minMax(int[] arr) { int minIndex = 0, maxIndex = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] < arr[minIndex]) minIndex = i; if (arr[i] > arr[maxIndex]) maxIndex = i; } int temp = arr[0]; arr[0] = arr[minIndex]; arr[minIndex] = temp; temp = arr[arr.length - 1]; arr[arr.length - 1] = arr[maxIndex]; arr[maxIndex] = temp; } public static void main(String[] args) { int[] arr = {4, 3, 2, 6, 1, 5}; System.out.println(Arrays.toString(arr)); minMax(arr); System.out.println(Arrays.toString(arr)); } }