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

Commit f5d5800

Browse files
author
Ram swaroop
committed
segregate even and odd nos : done
1 parent 0e76b0d commit f5d5800

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package me.ramswaroop.arrays;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Created by IntelliJ IDEA.
7+
*
8+
* @author: ramswaroop
9+
* @date: 7/31/15
10+
* @time: 5:13 PM
11+
*/
12+
public class SegregateEvenAndOddNos {
13+
14+
/**
15+
* Segregate even and odd numbers by traversing the
16+
* array {@param a} only once.
17+
* <p/>
18+
* This is similar to {@link me.ramswaroop.arrays.Segregate0sAnd1s}.
19+
*
20+
* @param a
21+
*/
22+
public static void segregateEvenAndOddNos(int[] a) {
23+
for (int i = 0, j = a.length - 1; i < j; ) {
24+
if (a[i] % 2 != 0 && a[j] % 2 == 0) {
25+
// swap
26+
a[i] = a[i] + a[j];
27+
a[j] = a[i] - a[j];
28+
a[i] = a[i] - a[j];
29+
i++;
30+
j--;
31+
} else if (a[i] % 2 == 0 && a[j] % 2 == 0) {
32+
i++;
33+
} else if (a[i] % 2 != 0 && a[j] % 2 != 0) {
34+
j--;
35+
} else {
36+
i++;
37+
j--;
38+
}
39+
}
40+
}
41+
42+
public static void main(String a[]) {
43+
int[] ar = new int[]{12, 34, 45, 9, 8, 90, 3};
44+
segregateEvenAndOddNos(ar);
45+
System.out.println(Arrays.toString(ar));
46+
int[] ar1 = new int[]{34, 1, 45, 9, 8, 67, 3, 56, 78, 79, 101, 100};
47+
segregateEvenAndOddNos(ar1);
48+
System.out.println(Arrays.toString(ar1));
49+
}
50+
}

0 commit comments

Comments
 (0)