Find a pair of elements with sum k (a+b=k) in sorted array
class FindAPaireWithSumKSortedArray {
static int[] array;
// Time complexity : O(n). Assuming +ve numbers
static void findPair(int k) {
int i = 0;
int j = array.length-1;
while(i < j) {
if(array[i] + array[j] == k) {
System.out.println("Found pair (" + array[i] + ", " + array[j] + ")");
i++;
j--;
continue; // To avoid checking below conditions
} else if(array[i] + array[j] > k) {
j--;
} else {
i++;
}
}
}
public static void main (String[] args) {
array = new int[] {1, 3, 4, 5, 6, 8, 9, 10, 12, 14};
int k = 10;
findPair(k);
array = new int[] {2, 3, 4, 5, 6, 7, 8, 9, 10, 12};
findPair(k);
}
}
Comments
Post a Comment