11/*
2- RADIX SORT
3- numbers to be sorted should be in a range eg (1-5) or (m to m+k)
2+ find a pair in an array whose sum is equal to a given number
3+ */
4+
5+ #include <stdio.h>
6+ #include <stdlib.h>
7+ #include <math.h>
8+
9+ /*METHOD1: by iterating and find suitable pairs
10+ Time complexity: O(n^2) time
11+ */
12+
13+ int main (){
14+
15+ int a [] = {2 ,5 ,8 ,1 ,4 ,5 };
16+ int j ;
17+
18+ printf ("pairs whose sum is 6 are\n" );
19+
20+ for (int i = 0 ; i < 6 ;i ++ ){
21+ int key1 = a [i ];
22+
23+ for (j = i + 1 ;j < 6 ;j ++ ){
24+ int key2 = a [j ];
25+
26+ if (key1 + key2 == 6 ){
27+ printf ("%d and %d " ,key1 ,key2 );
28+ printf ("\n" );
29+ }
430
31+ }
32+ }
533
6- Time complexity
7- O(n+k) k = range of numbers n= number of elemnts in input
34+ }
35+ /*METHOD2: hash table
36+ Insert all numbers into a hash table. O(n)
37+ For every element a, search b in hash table such that sum is x O(1)
838
9- Space complexity = size of DS
10- O(k)
39+ Time complexity: O(n) time
40+ Space complexity: size of hash O(n) time
1141*/
1242
1343#include <stdio.h>
14- #include <stdlib.h>
15- #include <math.h>
44+ #define MAX 10
45+
46+ void findPairs (int arr [],int size ,int sum ){
1647
48+ int index ,temp ;
49+ int hash [MAX ] = {0 };
1750
51+ for (index = 0 ; index < size ; index ++ ){
52+
53+ temp = sum - arr [index ];
54+ if (temp >=0 && hash [temp ] == 1 ){
55+ printf ("Pair with the given sum %d is %d and %d " , sum ,temp ,arr [index ]);
56+ }
57+ hash [arr [index ]]= 1 ;
58+ }
59+
60+ }
1861
1962int main (){
20- int a [] = {1 ,1 ,4 ,4 ,2 ,5 ,6 ,8 ,3 };
21-
22- }
63+ int a [] = {2 ,5 ,8 ,1 ,4 ,5 };
64+
65+ int length = sizeof (a )/sizeof (a [0 ]);
66+
67+ int sum = 9 ;
68+
69+ findPairs (a ,length , sum );
70+
71+ }
72+
0 commit comments