筆試題目:假設一整型數組存在若干正數和負數,現在通過某種算法使得該數組的所有負數在正數的左邊,
且保證負數件和正數間元素相對位置不變。時空復雜度要求分別為:o(n),o(1)。
例如
-3 4 2 -1 7 3 -5
排序后
-3 -1 -5 4 2 7 3
/*1.0版本思想*/
考慮復雜度,我的實現方法是找到第一個postive,再找到第一個negative after the postive,然后進行類似一趟冒泡的排序,重復做下去,直到cann't find negative after the first postive.
2.0版本是對1.0版的優化
#include<stdio.h> void swap(int *a,int *b) { int temp=*a; *a=*b; *b=temp; } int main() { int a[7]={ -3,4,2,-1,7,3,-5 }; /*2.0版本*/ int length=sizeof(a)/sizeof(int); int i,temp; for(i=0;i<length;i++){ if(a[i]<0){ temp=i-1; while(temp>=0 && a[temp]>0){ swap(&a[temp+1],&a[temp]); temp--; } } } /*1.0版本 寫的有點笨重*/ /* int pos_fir=-1,p,i; int n=sizeof(a)/sizeof(int); int temp; while(a[++pos_fir]<=0);//找到第一個正數位置 p=pos_fir; while(p<n){ while(a[++p]>0);//find first negative after first postive if(p<n){ //類似與一趟冒泡 for(i=p;i>pos_fir;i--){ temp=a[i]; a[i]=a[i-1]; a[i-1]=temp; } p=pos_fir++; } }*/ for(i=0;i<length;i++) printf("%d ",a[i]); }