您的位置:首页 > 其它

一整数数组,将奇数放在前面,偶数放在后面

2017-11-07 10:07 357 查看
package Test;

/*
 * 一整数数组,将奇数放在前面,偶数放在后面。两种方法(1)用快排思想。(2)用集合

 * */

import java.util.ArrayList;

import java.util.List;

public class jiouShunxu {

public static void main(String[] args) {
// TODO Auto-generated method stub

          int a[]={1,2,4,7,5,8,9,12,3};

          oderArray2(a);

//          for(int i:a){

//          System.out.print(i+" ");

//          }
}

private static void oderArray(int[] a) {  //快排思想 
// TODO Auto-generated method stub
 
int i=0;
int j=a.length-1;
while(i<j){

while(i<j&&a[i]%2!=0){
i++;
}
while(i<j&&a[j]%2==0){
j--;
}

if(i<j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}

}
}

private static void oderArray2(int[] a) {  //集合思想
// TODO Auto-generated method stub
int len=a.length;
List<Integer> a1=new ArrayList<Integer>();
List<Integer> a2=new ArrayList<Integer>();
for(int i=0;i<len;i++){
if(a[i]%2!=0){
a1.add(a[i]);
}else{
a2.add(a[i]);
}
}

 for(int tmp:a1){                             //增强for循环
 System.out.print(tmp+" ");
 }
 
 for(int tmp:a2){
 System.out.print(tmp+" ");
 }

// for(int i = 0; i < a1.size(); i++){               

//        System.out.print(a1.get(i)+" ");

//   }

// for(int i = 0; i < a2.size(); i++){

//        System.out.print(a2.get(i)+" ");

//   }
 
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐