(2)int A[nSize],其中隐藏着若干0,其余非0整数,写一个函数int Func(int* A, int nSize),使A把0移至后面,非0整数移至数组前面并保持有序,返回值为原数据中第一个元素为0的下标。(尽可能不使用辅助空间且考虑效率及异常问题,注释规范且给出设计思路)
#include "stdafx.h"
#include
using namespace std;
int Func(int *A, int nSize)
{
if (NULL == A || nSize <= 0)
{
return -1;
}
int count = 0;
int pos = -1;
for (int i = 0; i < nSize; i++)
{
if (-1 == pos && A[i] == 0)
{
pos = i;
count++;
}
else if (A[i] == 0)
{
count++;
}
else
{
for (int j = 0; j < count; j++)
{
A[i - j - 1] = A[i - j];
}
}
}
for (int i = count; i > 0; i--)
{
A[nSize - i] = 0;
}
return pos;
}
int _tmain(int argc, _TCHAR* argv[])
{
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<
}
int pos = Func(A, nSize);
cout<
for (int i = 0; i < nSize; i++)
{
cout<
}
cout<
cout<
system("pause");
return 0;
}