剑指offer 面试题14 数组元素奇数调整到偶数之前


#include <iostream>
using namespace std;
//两个指针夹逼 
void OddBeforeEven(int* array,int len){
	if(array==NULL||len<=0) return;
	int *begin=array;
	int *end=array+len-1;
	while(begin<end){
		while(begin<end&&(*begin&0x1)!=0)
			begin++;
		while(begin<end&&(*end&0x1)==0)
			end--;
		if(begin<end){
			int tmp=*begin;
			*begin=*end;
			*end=tmp;
		}
	}
}
//将A置于B之前的通用解法,函数参数 
void ABeforeB(int *array,int len,bool (*func)(int)){
	if(array==NULL||len<=0) return;
	int *begin=array;
	int *end=array+len-1;
	while(begin<end){
		while(begin<end&&!func(*begin))
			begin++;
		while(begin<end&&func(*end))
			end--;
		if(begin<end){
			int tmp=*begin;
			*begin=*end;
			*end=tmp;
		}
	}
}
bool isEven(int n){
	if((n&0x1)==0) return true;
	else return false;
}
void OddBeforeEven_2(int* array,int len){
	ABeforeB(array,len,isEven);
}

int main(){
	int array[5]={1,2,3,4,5};
	int array_2[5]={1,2,3,4,5};
	OddBeforeEven(array,5);
	OddBeforeEven_2(array_2,5);
	for(int i=0;i<5;++i){
		cout<<array[i];
	}
	for(int i=0;i<5;++i){
		cout<<array_2[i];
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值