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

来源:互联网 发布:淘宝全民晒单推广 编辑:程序博客网 时间:2024/04/29 07:13

剑指offer No.14,这题用双指针就可以了,代码如下

package com.zjy.sword2offer;public class ReorderArrByOddEven {public static void reorderArr(int[] a){if(a==null||a.length<=0)return;int Len = a.length;int pfront = 0;int pback = Len-1;while(true){while(pfront<Len-1){if((a[pfront]&1)==1)pfront++;elsebreak;}while(pback>0){if((a[pback]&1)==0)pback--;elsebreak;}if(pfront>=pback)break;else{int tmp = a[pfront];a[pfront] = a[pback];a[pback] = tmp;}}}public static void main(String[] args) {// TODO Auto-generated method stubint[] a = {2};reorderArr(null);for(int i=0;i<a.length;i++)System.out.println(a[i]);}}


0 0
原创粉丝点击