-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMain.java
51 lines (44 loc) · 1.47 KB
/
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package infytq;
import java.util.Arrays;
class Main
{
// Function to print all quadruplet present in an array with a given sum
public static void quadTuple(int[] A, int target)
{
// sort the array in ascending order
Arrays.sort(A);
// check if quadruplet is formed by `A[i]`, `A[j]`, and a pair from
// subarray `A[j+1…n)`
for (int i = 0; i <= A.length - 4; i++)
{
for (int j = i + 1; j <= A.length - 3; j++)
{
// `k` stores remaining sum
int k = target - (A[i] + A[j]);
// check for sum `k` in subarray `A[j+1…n)`
int low = j + 1, high = A.length - 1;
while (low < high)
{
if (A[low] + A[high] < k) {
low++;
}
else if (A[low] + A[high] > k) {
high--;
}
// quadruplet with a given sum found
else {
System.out.println("(" + A[i] + " " + A[j] + " " + A[low] + " " + A[high] + ")");
low++;
high--;
}
}
}
}
}
public static void main(String[] args)
{
int[] A = { 2, 7, 4, 0, 9, 5, 1, 3 };
int target = 20;
quadTuple(A, target);
}
}