将一组整数数组中的数字按负数在前,零在中间,正数在末尾摆放。

将一组整数中的数字按负数在前,零在中间,正数在末尾摆放。

美团电话面试程序题:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*
 *将一组整数排成负数,0,整数 
 */
 void swap(int *x,int *y){
 	int temp=*x;
 	*x=*y;
 	*y=temp;
 }
 void print(int a[],int n){
	int i; 	
	 for(i=0;i<n;i++){
 		printf("%d , ",a[i]);
	 }
 }
int main(int argc, char *argv[]) {
	/*
	printf("输入整数的个数");
	int n;
	int *a;
	scanf("%d\n",&n);
	printf("输入%d个整数",n);
	for(int i=0;i<n;i++){
		scanf("%d",*(a+i));
	}
	*/
	int i;
	int a[18]={0,3,6,4,-1,0,-2,0,4,7,-3,6,0,1,-4,1,0,0};
	int *p,*q,*r,*k;
	p=a;q=p+18-1;
	while(p<q){
		if(*p<0){
			p++;
		}else{
			if(*q>=0){
				q--;
			}else if(*q<0){
				swap(p,q);
				q--;
			}
		}
	}
	print(a,18);
	k=p;
	r=a+17;
	while(k<r){
		if(*k>0){
			if(*r==0){
				swap(k,r);
				k++;
			}else{
				r--;
			}
		}else{
			k++;
		}
	}
	print(a,18);
	getchar();
	return 0;
}

  第一次循环将负数排到前面,第二次循环将0排到负数后面,时间复杂度O(p)+ O(n-p)=O(N),空间复杂度O(1)

posted @ 2014-10-30 00:43  cc_jony  阅读(556)  评论(0编辑  收藏  举报