Skip to content

Commit 1fda9f6

Browse files
Merge pull request TheAlgorithms#1467 from varunvjha/varun-patch
Added Two Pointers Algorithm
2 parents b5fea3c + 55bd96b commit 1fda9f6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Others/TwoPointers.java

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package Others;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* The two pointer technique is a useful tool to utilize when searching for pairs in a sorted array.
7+
* <p>
8+
* link: https://www.geeksforgeeks.org/two-pointers-technique/
9+
*/
10+
class TwoPointers {
11+
12+
public static void main(String[] args) {
13+
int[] arr = {10, 20, 35, 50, 75, 80};
14+
int key = 70;
15+
assert isPairedSum(arr, key); /* 20 + 60 == 70 */
16+
17+
arr = new int[]{1, 2, 3, 4, 5, 6, 7};
18+
key = 13;
19+
assert isPairedSum(arr, key); /* 6 + 7 == 13 */
20+
21+
key = 14;
22+
assert !isPairedSum(arr, key);
23+
}
24+
25+
/**
26+
* Given a sorted array arr (sorted in ascending order).
27+
* Find if there exists any pair of elements such that their sum is equal to key.
28+
*
29+
* @param arr the array contains elements
30+
* @param key the number to search
31+
* @return {@code true} if there exists a pair of elements, {@code false} otherwise.
32+
*/
33+
private static boolean isPairedSum(int[] arr, int key) {
34+
/* array sorting is necessary for this algorithm to function correctly */
35+
Arrays.sort(arr);
36+
int i = 0; /* index of first element */
37+
int j = arr.length - 1; /* index of last element */
38+
39+
while (i < j) {
40+
if (arr[i] + arr[j] == key) {
41+
return true;
42+
} else if (arr[i] + arr[j] < key) {
43+
i++;
44+
} else {
45+
j--;
46+
}
47+
}
48+
return false;
49+
}
50+
}

0 commit comments

Comments
 (0)