Find Pair of Elements in Sorted Array Whose Sum is Equal to Required Number

package org.wesome.dsalgo;

import java.util.Arrays;

public class PairSum {
    static boolean pairSum(int arr[], int sum) {
        int lIndx, rIndx;
        lIndx = 0;
        rIndx = arr.length - 1;
        while (lIndx < rIndx) {
            if (arr[lIndx] + arr[rIndx] == sum) {
                System.out.println(arr[lIndx] + " and " + arr[rIndx] + " makes " + sum);
                return true;
            } else if (arr[lIndx] + arr[rIndx] < sum) lIndx++;
            else {
                rIndx--;
            }
        }
        return false;
    }
}
package org.wesome.dsalgo;

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

public class PairSumTest {
    @Test
    void PairSumTest1() {
        int arr[] = {-8, 1, 4, 6, 10, 45};
        int sum = 16;
        Assertions.assertTrue(PairSum.pairSum(arr, sum));
    }

    @Test
    void PairSumTest2() {
        int arr[] = {-5, -1, 2, 3, 4};
        int sum = -6;
        Assertions.assertTrue(PairSum.pairSum(arr, sum));
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

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

test {
    useJUnitPlatform()
}

 

follow us on