奇偶分割数组

来源:互联网 发布:打轴用什么软件 编辑:程序博客网 时间:2024/05/17 01:04
分割一个整数数组,使得奇数在前偶数在后。
样例

给定 [1, 2, 3, 4],返回 [1, 3, 2, 4]。


import java.util.Scanner;/** * 分割一个整数数组,使得奇数在前偶数在后。样例给定 [1, 2, 3, 4],返回 [1, 3, 2, 4]。 *  * @author Dell * */public class Test373 { public static void partitionArray(int[] nums){   if(nums==null|nums.length==1)   return;  int q=-1,p=0;  while(p<nums.length)  {  if(nums[p]%2==1)  {    q++; int temp=nums[p]; nums[p]=nums[q]; nums[q]=temp;  }  p++;  }}public static void main(String[] args) {      Scanner sc=new Scanner(System.in);         int n=sc.nextInt();         int[] a=new int[n];         for(int i=0;i<a.length;i++)         {         a[i]=sc.nextInt();         }         partitionArray(a);         for(int i=0;i<a.length;i++)         {         System.out.print(a[i]+" ");         }}}