forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSegregateEvenAndOddNos.java
50 lines (46 loc) · 1.29 KB
/
SegregateEvenAndOddNos.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
package com.rampatra.arrays;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 7/31/15
* @time: 5:13 PM
*/
public class SegregateEvenAndOddNos {
/**
* Segregate even and odd numbers by traversing the
* array {@param a} only once.
* <p/>
* This is similar to {@link Segregate0sAnd1s}.
*
* @param a
*/
public static void segregateEvenAndOddNos(int[] a) {
for (int i = 0, j = a.length - 1; i < j; ) {
if (a[i] % 2 != 0 && a[j] % 2 == 0) {
// swap
a[i] = a[i] + a[j];
a[j] = a[i] - a[j];
a[i] = a[i] - a[j];
i++;
j--;
} else if (a[i] % 2 == 0 && a[j] % 2 == 0) {
i++;
} else if (a[i] % 2 != 0 && a[j] % 2 != 0) {
j--;
} else {
i++;
j--;
}
}
}
public static void main(String[] args) {
int[] ar = new int[]{12, 34, 45, 9, 8, 90, 3};
segregateEvenAndOddNos(ar);
System.out.println(Arrays.toString(ar));
int[] ar1 = new int[]{34, 1, 45, 9, 8, 67, 3, 56, 78, 79, 101, 100};
segregateEvenAndOddNos(ar1);
System.out.println(Arrays.toString(ar1));
}
}