@@ -21,14 +21,18 @@ using namespace std;
2121// Prototypes for the algorithms
2222void findPairofNumbersToAddUpToAnother (int * ,int , int );
2323
24+ // For method 2;
25+ void findPairofNumbersToAddUpToAnother_optimized (int * arr,int len, int targetAdditionSum);
26+ void someSortingAlgorithm (int * arr,int length);
27+
2428int main (){
2529// Lines to handle user input go here, be descriptive...
2630// use cin, cout
27- int arr[] = {2 , 4 ,5 ,7 , 1 , 3 };
28- int additionNumber = 12 ;
31+ int arr[] = {1 , 2 , 5 ,5 ,15 , 22 , 55 };
32+ int additionNumber = 20 ;
2933int arrayLength = sizeof (arr)/sizeof (arr[0 ]);
3034// Call your algorithms here
31- findPairofNumbersToAddUpToAnother (arr, arrayLength, additionNumber);
35+ findPairofNumbersToAddUpToAnother_optimized (arr, arrayLength, additionNumber);
3236
3337
3438
@@ -60,3 +64,52 @@ void findPairofNumbersToAddUpToAnother(int* arr,int len, int targetAdditionSum){
6064
6165
6266}
67+
68+
69+ /* *********************************************************
70+ /* <findPairofNumbersToAddUpToAnother>
71+ /*
72+ /* @description : description here
73+ /* @param : Integer<variable> (Datatype<variable_name>)
74+ /* @return : datatype (int,float,double etc)
75+ /* @complexity : Big O notation. (O(n),O(n^2) etc)
76+ /* @explanation : Detailed description about what the algorithm does
77+ /* @author : <Your name> @<GitHub handle> (John Doe @johndoe)
78+ /**********************************************************/
79+ void findPairofNumbersToAddUpToAnother_optimized (int * arr,int len, int targetAdditionSum){
80+
81+ int left=0 ;
82+ int right=len-1 ;
83+
84+ someSortingAlgorithm (arr,len);
85+
86+ while (left<right){
87+ if (arr[left]+arr[right] > targetAdditionSum){
88+ right--;
89+ }
90+ if (arr[left]+arr[right] < targetAdditionSum){
91+ left++;
92+ }
93+ if (arr[left]+arr[right] == targetAdditionSum){
94+
95+ cout<<" Pair found :" <<arr[left]<< " " <<arr[right]<<endl;
96+ right--;
97+ left++;
98+ }
99+
100+ }
101+ }
102+
103+
104+ // Need this for Method 2, coz this optimized method only works for a sorted array.
105+ void someSortingAlgorithm (int * arr,int length){
106+ for (int i=0 ;i<length;i++){
107+ for (int j=i+1 ;j<length;j++){
108+ if (arr[i]>arr[j]){
109+ int temp=arr[i];
110+ arr[i] = arr[j];
111+ arr[j] = temp;
112+ }
113+ }
114+ }
115+ }
0 commit comments