forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmallestOf3Integers.java
57 lines (52 loc) · 1.15 KB
/
SmallestOf3Integers.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
56
57
package com.rampatra.bits;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 6/12/15
* @time: 6:18 PM
*/
public class SmallestOf3Integers {
/**
* Returns min of 2 numbers without using
* any comparison operators.
*
* @param x
* @param y
* @return
*/
private static int min(int x, int y) {
return y + ((x - y) & ((x - y) >> 31));
}
/**
* Returns the smallest element in an
* array of length 3.
*
* @param a
* @return
*/
public static int getSmallest(int a[]) {
return min(a[0], min(a[1], a[2]));
}
/**
* This method uses repeated subtraction to
* find the smallest element in an array.
*
* @param a
* @return
*/
public static int getSmallest_V1(int a[]) {
int c = 0;
while (a[0] > 0 && a[1] > 0 && a[2] > 0) {
a[0]--;
a[1]--;
a[2]--;
c++;
}
return c;
}
public static void main(String[] args) {
System.out.println(getSmallest(new int[]{4, 5, 6}));
System.out.println(getSmallest_V1(new int[]{4, 5, 6}));
}
}