In this tutorial, we will write a java program to find the sum pair in an array. Before that, you may go through the following topics in java.
The program takes a user input for a number of elements in an array and then the value of elements. After that, the program asks for the number to be checked for the sum and the calculation is done.
Find a Pair with the Given Sum in an Array in 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 | import java.util.Scanner; public class Main { public static void main(String[] args) { int[] arr = new int[10]; int n, value, num = 0; Scanner sc = new Scanner(System.in); System.out.println("How many elements"); n = sc.nextInt(); System.out.println("Enter the elements: "); for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); System.out.println("Enter the value to be checked: "); value = sc.nextInt(); for (int i = 0; i < (n - 1); i++) for (int j = (i + 1); j < n; j++) if (arr[i] + arr[j] == value) { System.out.println("Pair:(" + arr[i] + ", " + arr[j] + ")"); num = 1; } if (num == 0) System.out.println("Pair not found!"); } } |
Output 1:
How many elements
5
Enter the elements:
1
2
3
4
5
Enter the value to be checked:
80
Pair not found!
Output 2:
How many elements
5
Enter the elements:
1
2
3
4
5
Enter the value to be checked:
7
Pair:(2, 5)
Pair:(3, 4)
The time complexity for the worst case.
Big O: O(n2)
All the single line statement states represent with -> 1
And loop are represented with the number of times it loops and each of the program loops for “n” number of times, hence each loop represents n complexity.
Now the last for loop has one more for loop nested inside and since for leep here represents n complexity, therefore the last nested loop gices “n2” (n to the power 2) complexity.
And highest being the “n2”, therefor big O is n2.