分類排序問題

一個數組中有三種數,負數,零和正數,現在要求只對數組掃描一遍,即完成將數組分爲三部分,負數、零和正數。嘗試寫了一下代碼。


#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--;
        }
    }
    ;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章