Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 2f627ca

Browse files
author
Ram swaroop
committed
smallest element without comparison operators done
1 parent 1735ac9 commit 2f627ca

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package me.ramswaroop.bits;
2+
3+
/**
4+
* Created by IntelliJ IDEA.
5+
*
6+
* @author: ramswaroop
7+
* @date: 6/12/15
8+
* @time: 6:18 PM
9+
*/
10+
public class SmallestOf3Integers {
11+
12+
/**
13+
* Returns min of 2 numbers without using
14+
* any comparison operators.
15+
*
16+
* @param x
17+
* @param y
18+
* @return
19+
*/
20+
private static int min(int x, int y) {
21+
return y + ((x - y) & ((x - y) >> 31));
22+
}
23+
24+
/**
25+
* Returns the smallest element in an
26+
* array of length 3.
27+
*
28+
* @param a
29+
* @return
30+
*/
31+
public static int getSmallest(int a[]) {
32+
return min(a[0], min(a[1], a[2]));
33+
}
34+
35+
/**
36+
* This method uses repeated subtraction to
37+
* find the smallest element in an array.
38+
*
39+
* @param a
40+
* @return
41+
*/
42+
public static int getSmallest_V1(int a[]) {
43+
int c = 0;
44+
while (a[0] > 0 && a[1] > 0 && a[2] > 0) {
45+
a[0]--;
46+
a[1]--;
47+
a[2]--;
48+
c++;
49+
}
50+
return c;
51+
}
52+
53+
public static void main(String a[]) {
54+
System.out.println(getSmallest(new int[]{4, 5, 6}));
55+
System.out.println(getSmallest_V1(new int[]{4, 5, 6}));
56+
}
57+
}

0 commit comments

Comments
 (0)