Here is the code ....
public class test3 {
public static int getSumOfTwoClosestToZeroElements(int[] a) {
/*
Please implement this method to
return the sum of the two elements closest to zero.
If there are two elements equally close to zero like -2 and 2,
consider the positive element to be "closer" to zero than the negative one.
*/
int sum = 0;
int h = 0;
int[] d = new int[a.length + 1];
d[0] = 0;
for (int i = 1; i < a.length + 1; i++) {
d[i] = a[h];
h++;
}
int i = partition(d, 0, d.length);
//System.out.println(i);
for (int e = 0; e < d.length; e++)
System.out.print(d[e] + " ");
System.out.println();
int g = min(d, i + 1, d.length - 1);
int g1 = max(d, 0, i - 1);
// System.out.println(g1);
sum = g + g1;
return sum;
}
public static int partition(int[] s, int i, int l) {
int p = i;
int a = i;
for (int k = i + 1; k < s.length; k++) {
if (s[p] > s[k]) {
int temp;
a++;
temp = s[a];
s[a] = s[k];
s[k] = temp;
}
}
int temp = s[a];
s[a] = s[p];
s[p] = temp;
return a;
}
public static int min(int[] a, int f, int c) {
int i = a[f];
for (int s = f; s <= c; s++) {
{
if (i > a[s]) {
i = a[s];
}
}
}
return i;
}
public static int max(int[] a, int f, int c) {
int i = a[f];
for (int s = f; s <= c; s++) {
{
if (i < a[s]) {
i = a[s];
}
}
}
return i;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] w = {
1,
-2,
3,
5,
6,
7,
8,
-3,
-6,
2
};
System.out.println("The required sum is- " + getSumOfTwoClosestToZeroElements(w));
}
}
No comments:
Post a Comment