Sunday, February 19, 2023
HomeSoftware EngineeringLearn how to Remedy Max-Min Arrays in Java

# Learn how to Remedy Max-Min Arrays in Java

## The problem#

You might be given an array of distinctive parts, and your activity is to rearrange the values in order that the primary max worth is adopted by the primary minimal, adopted by second max worth then second min worth, and so on.

For instance:

``````remedy([15,11,10,7,12]) = [15,7,12,10,11]
``````

The primary max isÂ `15`Â and the primary min isÂ `7`. The second max isÂ `12`Â and the second min isÂ `10`Â and so forth.

## The answer in Java code#

Choice 1:

``````import java.util.*;

public static int[] remedy (int[] arr){
Arrays.type(arr);
int[] solutionArray = new int[arr.length];

for(int i = 0; i < arr.size; i++){
solutionArray[i] = i % 2 == 0 ? arr[arr.length - i/2 - 1] : arr[i/2];
}
return solutionArray;
}
}
``````

Choice 2:

``````import java.util.*;

public static int[] remedy (int[] arr){
Listing<Integer> temp = new ArrayList<Integer>();
Arrays.type(arr);
for (int i = 0, j = arr.size - 1; i <= j; ++i, --j) {
}
return temp.stream().mapToInt(i -> i).toArray();
}
}
``````

Choice 3:

``````import java.util.stream.IntStream;

public static int[] remedy(int[] arr) {
int[] sorted = IntStream.of(arr).sorted().toArray();
int[] end result = new int[arr.length];
for (int i = 0, j = arr.size - 1, f = -1; i < arr.size;) {
end result[i] = sorted[j];
j = (j + arr.size + (f *= -1) * (++i)) % arr.size;
}
return end result;
}

}
``````

## Take a look at circumstances to validate our resolution#

``````import org.junit.Take a look at;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;

public class SolutionTest{
@Take a look at
public void basicTests(){
}
}
``````

RELATED ARTICLES