java面试之操作数组

奇数在前偶数在后

Description

  • 给定一整型数组,操作数组使奇数在前偶数在后。

参考代码

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
public class {
public static void main(String[] args) {
int [] a = {1,4,2,3,5,6,9,8,7,0};
Sort(a);
}
public static void Sort(int[] a) {
int start = 0;
int end = a.length-1;
int temp = 0;
while (start<end) {
while (start<end && ((a[start]&1)==1)) {
start++;
}
while (start<end && ((a[end]&1)==0)) {
end--;
}
temp = a[start];
a[start] = a[end];
a[end] = temp;
}
//输出
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
}
}
}