forked from TECHOUS/DSKaKhel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindPairWithGivenSum_InRotatedArray.cpp
More file actions
96 lines (73 loc) · 1.87 KB
/
findPairWithGivenSum_InRotatedArray.cpp
File metadata and controls
96 lines (73 loc) · 1.87 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<iostream>
#include<algorithm>
#include<limits>
#include<map>
#include<iterator>
using namespace std;
/*
BruteForce with least complexity :
MergeSort => O(nlog(n));
BinarySearch => O(log(n));
T(n) = T(nlog(n))+T(log(n));
MAX COMPLEXITY O( n * log(n));
*/
int binarySearch(int * arr , int start , int end , int key){
if(start > end){
return 0 ;
}
int mid = (start + end)/2;
if(arr[mid] == key){
return mid;
}
else if(key > arr[mid]){
binarySearch(arr,mid+1,end,key);
}
else{
binarySearch(arr,start,mid-1,key);
}
}
void findSumIn_Rotated_Sorted_Array(int *arr,int size , int sum){
map<int,int> storePairs;
map<int,int> :: iterator it;
bool flag = false;
/* CODE WITH THE MAXIMUM COMPLEXITY */
// Sort the array , best would have been mergeSort
sort(arr,arr+size);
int i = 0;
while(i < size){
int temp = arr[i];
int findNextSum = (sum - temp);
int index = binarySearch(arr,0,size-1,findNextSum);
if(index == 0){
}
else{
storePairs.insert(pair<int,int>(temp,arr[index]));
flag = true;
}
i++;
}
if(flag == true){
cout<<"true"<<endl;
cout<<"The pairs are"<<endl;
for(it = storePairs.begin(); it!= storePairs.end() ; it++){
cout<<"{ "<<it->first<<" , "<<it->second<<"}"<<endl;
}
}
else{
cout<<"false"<<endl;
}
}
int main(){
int size,*arr,sum;
cout<<"Enter the size"<<endl;
cin>>size;
arr = new int[size];
cout<<"Enter the elements of the array"<<endl;
for(int i = 0 ; i < size ; i++){
cin>>arr[i];
}
cout<<"Give the sum whose pair is to be found"<<endl;
cin>>sum;
findSumIn_Rotated_Sorted_Array(arr,size,sum);
delete[] arr;
}