码迷,mamicode.com
首页 > 编程语言 > 详细

面试题14:调整数组顺序使奇数位于偶数前面

时间:2015-06-25 21:10:41      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

// 面试题14_调整数组顺序使奇数位于偶数前面.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
void swap(int *begin,int *end)
{
    int temp;
    temp=*begin;
    *begin=*end;
    *end=temp;
}


void ReorderOddEven(int *pData,unsigned int length)
{
    if(pData==NULL||length==0)
        return;
    int *begin=pData,*end=(pData+length-1);
    while(begin<end)
    {
        while((*begin)%2==1)
            begin++;
        while((*end)%2==0)
            end--;
        if(begin<end)
            swap(begin,end);
    }

}


int _tmain(int argc, _TCHAR* argv[])
{
    int pData[]={1,2,3,4,5,6,7,8,9,10};
    ReorderOddEven(pData,sizeof(pData)/sizeof(int));
    for(int i=0;i<sizeof(pData)/sizeof(int);i++)
    {
        cout<<pData[i]<<" ";
    }
    cout<<endl;
    return 0;
}

思路:1、begin指向第1个位置,end指向最后一个位置;

2、begin找到第一个为偶数的,end找到第一个为奇数的位置;

3、交换

4、若begin>end,重复2;

面试题14:调整数组顺序使奇数位于偶数前面

标签:

原文地址:http://www.cnblogs.com/Mikuroro/p/4600808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!