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

来源:互联网 发布:时时彩做计划软件 编辑:程序博客网 时间:2024/05/02 22:37
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)+" ");
//   }
 
}

}
阅读全文
0 0
原创粉丝点击