Find Largest and Smallest in array

package com.company;

public class Algorithm {
    Number largestAndSmallest(int[] array) {
        if (array.length == 0) {
            throw new RuntimeException("Invalid length");
        }
        Number number = new Number();
        number.smallest = array[0];
        number.largest = array[0];
        for (int arr : array) {
            if (number.largest < arr) {
                number.largest = arr;
            } else if (number.smallest > arr) {
                number.smallest = arr;
            }
        }
        return number;
    }

    class Number {
        int largest;
        int smallest;
    }
}
package com.company;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class AlgorithmTest {
    @Test
    void largestAndSmallest1() {
        Algorithm algorithm = new Algorithm();
        int[] array = new int[]{2, 4, 6, 0, 1, 3, 5};
        Algorithm.Number number = algorithm.largestAndSmallest(array);
        Assertions.assertEquals(0, number.smallest);
        Assertions.assertEquals(6, number.largest);
    }

    @Test
    void largestAndSmallest2() {
        Algorithm algorithm = new Algorithm();
        int[] array = new int[]{10, 3, 5, -1, 0, -10};
        Algorithm.Number number = algorithm.largestAndSmallest(array);
        Assertions.assertEquals(-10, number.smallest);
        Assertions.assertEquals(10, number.largest);
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

test {
    useJUnitPlatform()
}

 

follow us on