forked from nibnait/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOdd_forward.java
More file actions
42 lines (34 loc) · 983 Bytes
/
Odd_forward.java
File metadata and controls
42 lines (34 loc) · 983 Bytes
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
package others;
import Standard.std;
import Standard.stdOut;
/**
* 奇数放在偶数的前面。(插入排序的变异)
* 【剑指Offer 14题】
* Created by nibnait on 2016/8/7.
*/
public class Odd_forward {
public static void main(String[] args) {
int[] a = {1, 2, 1, 3, 4, 5};
stdOut.print(a);
for (int i = 1; i < a.length; i++) {
for (int j = i; j > 0 && IsOdd(a[j]) && !IsOdd(a[j-1]); j--) {
std.swap(a,j,j-1);
}
}
//时间复杂度:O(n)的方法:
//两个指针
/* for (int i = 0; i < a.length; i++) {
if (!IsOdd(a[i])) {
for (int j = a.length - 1; j > 0 && i < j; j--) {
if (IsOdd(a[j])) {
std.swap(a, i, j);
}
}
}
}*/
stdOut.print(a);
}
private static boolean IsOdd(int i) {
return i % 2 == 1;
}
}