0 votes
50 views
in Data Structure And Algorithm by (3.7k points)
Given a sorted array and a number x, find the pair in array whose sum is x.

int arr[] = {5,6,7,8,10,20,30,40};
int sum = 28;

1 Answer

0 votes
by (3.9k points)

Find the pairs in sorted array whose sum is x. See the following code to find pairs in O(n) time complexity.

package com.dev.array;

public class FindPairsInSortedArray {

public static void main(String[] args) {

int arr[] = {5,6,7,8,10,20,30,40};

int sum = 28;

boolean isFound = isPairExistsInSortedArray(arr,sum);

System.out.println(isFound == true ? "Pair Found" : "Pair Not Found");

}

//Time Complexity O(n)

private static boolean isPairExistsInSortedArray(int[] arr, int sum) {

int start=0, end=arr.length-1;

while(start<=end) {

if(arr[start]+arr[end]==sum) {

System.out.println("Pair: ["+arr[start]+", "+ arr[end]+"]");

return true;

}

if(arr[start]+arr[end] > sum) {

end--;

}else {

start++;

}

}

System.out.println("Pair not found!");

return false;

}

}

Output:- Found: true

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...