剑指offer eg11 调整数组顺序使 奇数位于偶数前面

1 牛客网上的适用代码;   java

(参考别人)


public class Solution {
    public void reOrderArray(int [] array) {
        
    if(array.length==0||array.length==1) return;
        int oddCount=0,oddBegin=0;
        
        int[] newArray=new int[array.length];
        
        for(int i=0;i<array.length;i++){//统计奇数个数
            if((array[i]&1)==1) oddCount++;
        }
        
        for(int i=0;i<array.length;i++){
            if((array[i]&1)==1) newArray[oddBegin++]=array[i];
            else newArray[oddCount++]=array[i];
        }
        for(int i=0;i<array.length;i++){
            array[i]=newArray[i];
        }      


}
}


第二种 解法:

public class Solution {
    public void reOrderArray(int [] array) {

if (array == null || array.length == 0)
 return;
 int tmp = 0;
 for (int i = 0, j = 0; i < array.length && j < array.length; i++) 
 {
  if (array[i] % 2 != 0) 
    {
  tmp = array[i];
  for (int k = i; k > j; k--) 
        {
  array[k] = array[k - 1];
     }
  array[j] = tmp;
  j++;
  }
 }

}
}


2 自己在VC6上运行的C代码:

/*
考虑扩展性,解耦的好处在于提高代码的重用性,为功能扩展提供便利
  
*/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>


const int N=5;


bool recorde(int n)
{
return (n & 1)==0;
}


void f(int *a,int n,bool (*fu)(int))  
//bool (*fu)(int)  以整型为输入,布尔型为输出的
//回调函数
{
if(a==NULL||n==0)return ;
int *p=a;
int *q=a+n-1;


while(p<q)
{
while(p<q && !fu(*p)){p=p++;}
while(p<q && fu(*q)){q=q--;}


if(p<q)
{
int t;
t=*p;
*p=*q;
*q=t;
}
}
}


void output(int *a,int n)
{
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");


}


int main()
{
 
int b[N]={1,2,3,4,5};
f(b,N,recorde);
output(b,N);
 
system("pause");
return 0;
}


/*
以下code 只是适用初级程序猿,没有考虑扩展性
  
*/
/*#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>


const int N=5;
//#define N 5


void f(int *a,int n)
{
if(a==NULL||n==0)return ;
int *p=a;
int *q=a+n-1;


while(p<q)
{
while(p<q && (*p&0x1)!=0){p=p++;}
while(p<q && (*q%2)==0){q=q--;}


if(p<q)
{
int t;
t=*p;
*p=*q;
*q=t;
}
}


}


void output(int *a,int n)
{
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}


int main()
{
 
int b[N]={8,2,3,4,5};
f(b,N);
output(b,N);
//printf("%ld=",0x1);
system("pause");
return 0;
}
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值