diff --git a/Others/TwoPointers.java b/Others/TwoPointers.java new file mode 100644 index 00000000..99040b55 --- /dev/null +++ b/Others/TwoPointers.java @@ -0,0 +1,50 @@ +package Others; + +import java.util.Arrays; + +/** + * The two pointer technique is a useful tool to utilize when searching for pairs in a sorted array. + *

+ * link: https://www.geeksforgeeks.org/two-pointers-technique/ + */ +class TwoPointers { + + public static void main(String[] args) { + int[] arr = {10, 20, 35, 50, 75, 80}; + int key = 70; + assert isPairedSum(arr, key); /* 20 + 60 == 70 */ + + arr = new int[]{1, 2, 3, 4, 5, 6, 7}; + key = 13; + assert isPairedSum(arr, key); /* 6 + 7 == 13 */ + + key = 14; + assert !isPairedSum(arr, key); + } + + /** + * Given a sorted array arr (sorted in ascending order). + * Find if there exists any pair of elements such that their sum is equal to key. + * + * @param arr the array contains elements + * @param key the number to search + * @return {@code true} if there exists a pair of elements, {@code false} otherwise. + */ + private static boolean isPairedSum(int[] arr, int key) { + /* array sorting is necessary for this algorithm to function correctly */ + Arrays.sort(arr); + int i = 0; /* index of first element */ + int j = arr.length - 1; /* index of last element */ + + while (i < j) { + if (arr[i] + arr[j] == key) { + return true; + } else if (arr[i] + arr[j] < key) { + i++; + } else { + j--; + } + } + return false; + } +} \ No newline at end of file diff --git a/Others/TwoPointersAlgo.java b/Others/TwoPointersAlgo.java deleted file mode 100644 index 903c9d79..00000000 --- a/Others/TwoPointersAlgo.java +++ /dev/null @@ -1,75 +0,0 @@ -import java.util.*; -import java.lang.*; -import java.io.*; - -//https://www.geeksforgeeks.org/two-pointers-technique/ - -class TwoPointersAlgo { - //This function prints all pairs in the array that sum to a number X. If no such pair exists then output will be -1. - static void twoSum(int A[], int X) - { - Arrays.sort(A); - - //Array sorting is necessary for this algo to function correctly - - int n = A.length; - int i = 0, j = n-1, flag=0; - //Implementation of the algorithm starts - while(i0) - { - t--; - n = in.nextInt(); - int a[] = new int[n]; - for(int i = 0; i