华为的一道题

看了别人的解法没有看懂,自己写的

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

 

// 0再前非零在后.cpp : Defines the entry point for the console application.

//



#include "stdafx.h"



void swap(int *a, int *b)

{

	int temp;

	temp=*a;

	*a=*b;

	*b=temp;

}



void fun1(int a[], int n)

{

	int i;

	int j;

	int first=0;



	for (i=0;i<n;i++)

	{

		for (j=i+1;j<n;j++)

		{

			if (a[i]==0&&a[j]!=0)

			{

				first++;

				if (first==1)

				{

					printf("第一个不为零的下标是:%d\n",j);

				}

				swap(&a[i], &a[j]);

			}

		}

	}

}



int main(int argc, char* argv[])

{

	int a[7]={0,0,2,0,1,5,3};



	fun1(a,7);

	

	for (int i=0;i<6;i++)

	{

		printf("%d ", a[i]);

	}

	

	return 0;

}


 

 

你可能感兴趣的:(华为)