给出了一个整数数组,将数组中的偶数和奇数分开。所有的偶数都应该先出现,然后是奇数。
示例:
Input: arr[] = 1 9 5 3 2 6 7 11
Output: 2 6 5 3 1 9 7 11
Input: arr[] = 1 3 2 4 7 6 9 10
Output: 2 4 6 10 7 1 9 3
public class Segregate_even_odd_numbers {
public static void main(String[] args) {
int a[]= { 1, 3, 2, 4, 7, 6, 9, 10 };
int n=a.length;
int ind=0;
for(int i=0;i<n;i++){
if(a[i]%2==0){
a[ind]=a[i];
ind++;
}
}
for(int i=0;i<n;i++){
if(a[i]%2!=0){
a[ind]=a[i];
ind++;
}
}
for(int i=0;i<n;i++){
System.out.println(a[i] + " ");
}
System.out.println("");
}
}我得到了这样的输出
2
4
6
10
7
9
9
10 第0指数和第1指数不计算。
我犯了什么错误,请指点我。
发布于 2021-10-03 13:39:56
这也可以通过根据每个元素模2的值对数组进行排序来实现。
int[] a= { 1, 3, 2, 4, 7, 6, 9, 10 };
int[] res = Arrays.stream(a).boxed().sorted(Comparator.comparingInt(x -> x & 1))
.mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(res));发布于 2021-10-03 13:25:34
您的程序几乎是正确的,但不需要修改,下面是实现和解释
public class Segregate_even_odd_numbers {
public static void main(String[] args) {
int a[] = { 1, 9, 5, 3, 2, 6, 7, 11 };
int n = a.length;
int evenIndex = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
int temp = a[i];
a[i] = a[evenIndex];
a[evenIndex] = temp;
evenIndex++;
}
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
} }我们在这里做什么:
当我们找到任何偶数值时,我们就将它与arrevenIndex
的数组,则不会修改任何值。
时间复杂度: O(n)空间复杂度: O(1)
https://stackoverflow.com/questions/69425126
复制相似问题