一個數組中有三種數,負數,零和正數,現在要求只對數組掃描一遍,即完成將數組分為三部分,負數、零和正數。嘗試寫了一下代碼。
#include <stdio.h>
#define N 9
void swap(int *p,int *q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
return ;
}
int main()
{
int array[N]={-1,-3,0,-2,3,2,-2,0,1};
int *p_neg,*p,*p_pos;
for (p_neg=&array[0],p=&array[0],p_pos=&array[N-1]; p <= p_pos; p++)
{
if (*p < 0)
{
swap(p,p_neg);
p_neg++;
}
if (*p > 0)
{
swap(p,p_pos);
p_pos--;
p--;
}
}
;
}本文出自 “天才鳥蛋” 博客,請務必保留此出處http://curely.blog.51cto.com/1627940/1297308