-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
76 lines (61 loc) · 1.84 KB
/
main.c
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
#include <stdio.h>
#include <math.h>
void swap(int *xp, int *yp);
void sort(int array[], int array_size);
int * find_elements(int first_array[], int second_array[], int target, int array_size);
#define ARRAY_SIZE 6
int main() {
int first_array[] = {-1, 3, 8, 2, 9, 5};
int second_array[] = {4, -5, 2, 10, 5, 20};
int target = 10;
int *result;
result = find_elements(first_array,second_array,target,ARRAY_SIZE);
printf("[%d,%d]",result[0],result[1]);
return 0;
}
int * find_elements( int first_array[],
int second_array[],
int target,
int array_size
) {
sort(first_array,array_size);
sort(second_array,array_size);
int i = 0,j = array_size -1;
int smallest_diff = abs(first_array[0] + second_array[0] - target);
int closest_pair[] = {first_array[0],second_array[0]};
while(i < array_size && j>=0){
int first_pair = first_array[i];
int second_pair = second_array[j];
int current_diff = (first_pair + second_pair - target);
if(abs(current_diff) < smallest_diff){
smallest_diff = abs(current_diff);
closest_pair[0] = first_pair;
closest_pair[1] = second_pair;
}
if (current_diff == 0) {
return closest_pair;
}
else if (current_diff < 0) {
i += 1;
}
else {
j -= 1;
}
}
return closest_pair;
}
void sort( int array[], int array_size) {
int min_idx;
for (int i = 0; i < array_size - 1; i++) {
min_idx = i;
for (int j = i + 1; j < array_size; j++)
if (array[j] < array[min_idx])
min_idx = j;
swap(&array[min_idx], &array[i]);
}
}
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}