File tree 1 file changed +80
-0
lines changed 1 file changed +80
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+
3
+ using namespace std ;
4
+
5
+ int main ()
6
+ {
7
+ cout<<" Enter the size of array\n " ;
8
+ long n;
9
+ cin>>n;
10
+ cout<<" Enter " <<n<<" space seperated integers\n " ;
11
+ long *arr = new long [n];
12
+ for (long i=0 ;i<n;i++){
13
+ cin>>arr[i];
14
+ }
15
+
16
+ sort (arr, arr+n);// in ascending order
17
+ cout<<" Sorted array:\n " ;
18
+ for (long i=0 ;i<n;i++)
19
+ {
20
+ cout<<arr[i]<<" " ;
21
+ }
22
+ cout<<endl;
23
+
24
+ long sum;
25
+ cout<<" Enter the value of sum\n " ;
26
+ cin>>sum;
27
+
28
+ long left=0 ,right=n-1 ;
29
+ bool pair_exist = false ;
30
+
31
+ while (left<right){
32
+ long left_plus_right = arr[left] + arr[right];
33
+ if (left_plus_right==sum)
34
+ {
35
+ cout<<" Pair:(" <<arr[left]<<" ," <<arr[right]<<" )\n " ;
36
+ left++;// to find next pair whose sum is equal to given sum
37
+ pair_exist = true ;
38
+ }
39
+ else if (left_plus_right<sum)// move left pointer
40
+ left++;
41
+ else // move right pointer
42
+ right--;
43
+ }
44
+
45
+ if (pair_exist == false ){
46
+ cout<<" No pair exist with sum equal to " <<sum<<endl;
47
+ }
48
+
49
+ return 0 ;
50
+ }
51
+
52
+
53
+ /*
54
+ Test case1:
55
+ Enter the size of array
56
+ 8
57
+ Enter 8 space seperated integers
58
+ 12 3 5 6 2 7 8 4
59
+ Sorted array:
60
+ 2 3 4 5 6 7 8 12
61
+ Enter the value of sum
62
+ 8
63
+ Pair:(2,6)
64
+ Pair:(3,5)
65
+
66
+
67
+ Test case 2:
68
+ Enter the size of array
69
+ 10
70
+ Enter 10 space seperated integers
71
+ 1 2 3 5 6 4 7 8 10 5
72
+ Sorted array:
73
+ 1 2 3 4 5 5 6 7 8 10
74
+ Enter the value of sum
75
+ 9
76
+ Pair:(1,8)
77
+ Pair:(2,7)
78
+ Pair:(3,6)
79
+ Pair:(4,5)
80
+ */
You can’t perform that action at this time.
0 commit comments