整数数组0元素后移

来源:互联网 发布:免费snmp网络管理软件 编辑:程序博客网 时间:2024/05/17 16:56

题目:如下:int A[nSize],其中隐藏着若干0,其余非0整数,写一个函数int Func(int* A, int nSize),使A把0移至后面,非0整数移至数组前面并保持有序,返回值为原数据中第一个元素为0的下标。(尽可能不使用辅助空间且考虑效率及异常问题,注释规范且给出设计思路)。

#include<iostream>
using namespace std;
int Func(int* a, int nSize)
{
int* pAhead=a;
int* pBehind=a;
int i=0;
while(*pAhead!=0)
{
*pBehind++=*pAhead++;
i++;
}
while(pAhead-a<nSize)
{
if(*pAhead==0)
{
pAhead++;
continue;
}
*pBehind++=*pAhead++;
}
while(pBehind-a<nSize)
*pBehind++=0;
return i;
}


void main()
{
int A[] = {6 ,0 ,3, 4, 0, 5, 9, 6, 4, 6, 5, 8, 0, 0};
    int nSize = sizeof(A)/sizeof(A[0]);
    cout<<"before: ";
    for (int i = 0; i < nSize; i++)
    {
        cout<<A[i]<<"  ";
    }
    int pos = Func(A, nSize);
    cout<<endl<<"after:  ";
    for (i = 0; i < nSize; i++)
    {
        cout<<A[i]<<"  ";
    }
    cout<<endl<<"原数组第一个0元素的下标为: "<<pos<<endl;


    cout<<endl; 
}