Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int closestSmallerSearch(int[], int, int);
- bool hasPair(int[], int, int[], int);
- int main(void)
- {
- int size = 0;
- cout << "How many elements? : ";
- cin >> size;
- int *arr = new int[size];
- int pairs[2] = { 0 };
- for (int i = 0; i < size; i++)
- {
- cout << "\nElement no:" << i + 1 << " = ";
- cin >> arr[i];
- }
- cout << "\n---------------------\n";
- cout << "\nGiven sum : ";
- int sum = 0; cin >> sum;
- if (hasPair(arr, size, pairs, sum))
- {
- cout << "\nFirst occurence of pair : (" << pairs[0] << ", " << pairs[1] << ")\n\n";
- }
- else
- {
- cout << "\nNo such pair is found.\n\n";
- }
- return 0;
- }
- int closestSmallerSearch(int list[], int size, int value)
- {
- int low = 0, high = size - 1;
- int mid = 0;
- while (low <= high)
- {
- mid = low + ((high - low) / 2); // (low + high) / 2
- if (list[mid] == value)
- {
- return (mid - 1); // if matches then we need the index - 1 here
- }
- else if (list[mid] < value)
- {
- low = mid + 1;
- }
- else
- {
- high = mid - 1;
- }
- }
- if (low == high) // if not matches , we need the smaller nearest
- {
- if (list[low] < list[mid])
- {
- return low;
- }
- else if (list[low] > list[mid])
- {
- return (low - 1);
- }
- }
- }
- bool hasPair(int collection[], int size, int pairs[], int sum)
- {
- bool pairFound = false;
- int begin = 0, end = closestSmallerSearch(collection, size, sum);
- if (end != -1)
- {
- while (begin < end) {
- int total = collection[begin] + collection[end];
- if (total == sum)
- {
- pairs[0] = collection[begin];
- pairs[1] = collection[end];
- pairFound = true;
- break;
- }
- else if (total < sum)
- {
- begin++;
- }
- else
- {
- end--;
- }
- }
- }
- else
- {
- cout << "\nGiven sum is too small." << end;
- }
- return pairFound;
- }
Add Comment
Please, Sign In to add comment