Common element in 2 sorted arrays

package com.company;

public class Algorithm {
    int common(int[] array1, int[] array2) {
        int j = 0;
        int i = 0;
        while (i <= array1.length - 1 && j <= array2.length - 1) {
            if (array1[i] == array2[j]) {
                System.out.println("common int is = " + array1[i]);
                return array1[i];
            } else if (array1[i] > array2[j]) {
                j++;
            } else {
                i++;
            }
        }
        return 0;
    }
}
package com.company;

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

public class AlgorithmTest {
    @Test
    void common1() {
        Algorithm algorithm = new Algorithm();
        int common = algorithm.common(new int[]{2, 4, 6, 8}, new int[]{3, 6, 9});
        Assertions.assertEquals(6, common);
    }

    @Test
    void common2() {
        Algorithm algorithm = new Algorithm();
        int common = algorithm.common(new int[]{9, 12}, new int[]{8, 12});
        Assertions.assertEquals(12, common);
    }

    @Test
    void common3() {
        Algorithm algorithm = new Algorithm();
        int common = algorithm.common(new int[]{3, 6, 9}, new int[]{4, 8, 12});
        Assertions.assertEquals(0, common);
    }
}
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