將一組整數數組中的數字按負數在前,零在中間,正數在末尾擺放。

將一組整數中的數字按負數在前,零在中間,正數在末尾擺放。面試

美團電話面試程序題:oop

#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)this

相關文章
相關標籤/搜索