-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAssingment5Problem4.java
55 lines (48 loc) · 1.82 KB
/
Assingment5Problem4.java
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
public class Assingment5Problem4 {
public int getClosestOfTarget(int[] array, int target) {
int length = array.length;
if (length == 0) {
return -1;
}
for (int i = 0, j = 1; i < length - 1; ++i, ++j) {
if (target < array[0]) {
return 0;
} else if (target == array[i]) {
return i;
} else if (target > array[i] && target < array[j]) {
int result = getClosest(array[i], array[j], target);
if (result == array[i]) {
return i;
} else {
return j;
}
}
}
return length - 1;
}
public int getClosest(int i, int j, int target) {
if ((target - i) >= (j - target)) {
return j;
}
return i;
}
public static void main(String[] args) {
Assingment5Problem4 obj = new Assingment5Problem4();
int[] array1 = { 1, 3, 7, 8, 12, 23, 25 };
int target1 = 11;
int result = obj.getClosestOfTarget(array1, target1);
System.out.println("The index of tagert close to array item is : " + result);
int[] array2 = {};
int target2 = 11;
result = obj.getClosestOfTarget(array2, target2);
System.out.println("The index of tagert close to array item is : " + result);
int[] array3 = { 11, 22, 33, 44, 55, 66, 77 };
int target3 = 38;
result = obj.getClosestOfTarget(array3, target3);
System.out.println("The index of tagert close to array item is : " + result);
int[] array4 = { 11, 22, 33, 44, 55, 66, 77 };
int target4 = 80;
result = obj.getClosestOfTarget(array4, target4);
System.out.println("The index of tagert close to array item is : " + result);
}
}