Write a function that takes an integer array, and without sorting the array returns its largest and smallest number as a two element array.
INPUT: OUTPUT:
{-1,-2,-3,-4,-5,-6,-7,-8,-9,-1} -> {-9,-1}
public class HighLow{
public static int[] printLargestAndSmallest(int[] nums){
int low[] = nums;
int high[] = nums;
int lowest = nums[0];
int highest = nums[0];
int count = 0;
for(int i = 0; i < nums.length;i+=2){
int num1 = nums[i];
int num2 = nums[i+1];
if(num1<num2){
low[count] = num1;
high[count] = num2;
count++;
}else{
low[count] = num2;
high[count] = num1;
count++;
}
lowest = low[0];
highest = high[0];
for(int j = 1; j < low.length; j++){
if(low[j] < lowest){
lowest = low[j];
}
}
for(int j = 1; j < high.length; j++){
if(high[j] > highest){
highest = high[j];
}
}
}
int[] finalHighLow = new int[2];
finalHighLow[0] = lowest;
finalHighLow[1] = highest;
return finalHighLow;
}
}
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD by writing your own tests
public class SolutionTest {
int[] input = new int[]{-1,-2,-3,-4,-5,-6,-7,-8,-9,-1};
int[] output = new int[]{-9,-1};
@Test
public void allNegatives() {
assertArrayEquals(output, HighLow.printLargestAndSmallest(input));
}
int[] input2 = new int[]{1,-2,3,-4,-5,-6,-7,-8,-9};
int[] output2 = new int[]{-9,3};
@Test
public void test2() {
assertArrayEquals(output, HighLow.printLargestAndSmallest(input));
}
}