-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSUM
More file actions
94 lines (79 loc) · 1.99 KB
/
SUM
File metadata and controls
94 lines (79 loc) · 1.99 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
//Given an array of n elements. Find two elements in the array such that their sum is equal to given element k
# include <stdio.h>
#include<stdlib.h>
# define bool int
void quickSort(int *, int, int);
bool hasArray(int A[], int arr_size, int sum)
{
int l, r;
quickSort(A, 0, arr_size-1); //Sorting the elements of the array using quick sort
l = 0;
r = arr_size-1;
while (l < r)
{
if(A[l] + A[r] == sum)
{
printf("The numbers that add up to given element are : %d and %d",A[l],A[r]);
return 1;
}
else if(A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return 0;
}
void exchange(int *a, int *b) // Function for swapping the elements
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition(int A[], int si, int ei)
{
int x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++)
{
if(A[j] <= x)
{
i++;
exchange(&A[i], &A[j]);
}
}
exchange (&A[i + 1], &A[ei]);
return (i + 1);
}
void quickSort(int A[], int si, int ei) //Quick sort
{
int pi; //Partitioning index
if(si < ei)
{
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
int main()
{
int sum;
int n;
int *array;
printf("Enter the no. of elements");
scanf("%d",&n);
array=calloc(n,sizeof(int));
printf("Enter the elements ");
for(int i=0;i<n;i++)
{
scanf("%d",(array+i));
}
printf("Enter the sum ");
scanf("%d",&sum);
if(hasArray(array,n,sum))
printf("\nArray has two elements with given sum");
else
printf("\nArray doesn't have two elements with given sum");
return 0;
}