调整数组顺序使奇数位于偶数前面

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

自己用了额外空间实现函数:

 1 import java.util.*;
 2 public class Solution {
 3     public void reOrderArray(int [] array) {
 4         Stack<Integer> s = new Stack<Integer>();
 5         int l = array.length;
 6         for(int i=0;i<l;i++){
 7             if(array[i]%2==1){
 8                 s.push(array[i]);
 9             }
10         }
11         for(int j=0;j<l;j++){
12             if(array[j]%2==0){
13                 s.push(array[j]);
14             }
15         }
16         for(int k=l-1;k>=0;k--){
17             array[k] = s.pop();
18         }
19     }
20 }

本题不使用额外空间的方法:

 1 public class Solution {
 2     public void reOrderArray(int [] array) {
 3        for(int i= 0;i<array.length-1;i++){
 4             for(int j=0;j<array.length-1-i;j++){
 5                 if(array[j]%2==0&&array[j+1]%2==1){
 6                     int t = array[j];
 7                     array[j]=array[j+1];
 8                     array[j+1]=t;
 9                 }
10             }
11         }
12     }
13 }

因为要相对位置不变所以要相邻交换即左偶右奇就交换

原文地址:https://www.cnblogs.com/haq123/p/12117038.html