Common element in 3 sorted arrays

package com.company;

public class Algorithm {
    int common(int[] array1, int[] array2, int[] array3) {
        int i = 0;
        int j = 0;
        int k = 0;
        while (i <= array1.length - 1 && j <= array2.length - 1 && k <= array3.length - 1) {
            if (array1[i] == array2[j] && array2[j] == array3[k]) {
                System.out.println("common int is = " + array1[i]);
                return array1[i];
            } else if (array1[i] > array2[j]) {
                j++;
            } else if (array2[j] > array3[k]) {
                k++;
            } 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[]{3, 6, 9}, 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}, new int[]{12, 4, 6, 8});
        Assertions.assertEquals(12, common);
    }

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