多点坐标排序算法

来源:互联网 发布:c语言数学要求高吗 编辑:程序博客网 时间:2024/05/11 17:35

最近做项目中需要一个对多点坐标进行排序的算法,最后终于得到了自己满意的算法,公布如下:

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

struct POINT
{
    float x,y;
};

int pt_cmp(const void* val_l, const void* val_r)
{
    POINT* left = (POINT*)val_l;
    POINT* right = (POINT*)val_r;

    if (left->x > right->x)    //按x坐标排序。如果要按y坐标,则把pt_cmp函数中的x换成y
    {
        return 1;
    }
    else if (left->x == right->x)
    {
        if (left->y > right->y)
        {
            return 1;
        }
        else if (left->y == right->y)
        {
            return 0;
        }
        else
            return -1;
    }
    return -1;
}

void Output(POINT* pArr, int nCnt)
{
    for(int i=0; i<nCnt; i++)
    {
        printf("(%.2f, %.2f)\n", pArr[i].x, pArr[i].y);
    }
    printf("...........................................\n");
}

void sort(POINT* a,int n)
{
       int i;
       int j;
       for(i=0;i<n-1;i++)
                for(j=0;j<n-1;j++)
                {
                          if(a[j].x>a[j+1].x)
                           {
                                   POINT t=a[j];
                                   a[j]=a[j+1];
                                   a[j+1]=t;
                            }
                             else if(a[j].x==a[j+1].x)
                             {
                                      if(a[j].y>a[j+1].y)
                                      {
                                               POINT t=a[j];
                                              a[j]=a[j+1];
                                              a[j+1]=t;
                                     }
                             }
                 }
}


int main()
{
    //(9,20.95)(1.25,6)(10,36)(27,8)(27,0.05)(27,1)
    //(27,30)(90,110)(27.05,17.9)(90,3)(……)
    POINT pt_arr[] = {{9, 20.95}, {1.25, 6}, {10, 36}, {27, 8}, {27, 0.05}, {27, 1}
                    , {27, 30}, {90, 110}, {27.05, 17.9}, {90, 3}};

    Output(pt_arr, sizeof(pt_arr)/sizeof(POINT));

    //qsort(pt_arr, sizeof(pt_arr)/sizeof(POINT), sizeof(POINT), pt_cmp);
 sort(pt_arr, sizeof(pt_arr)/sizeof(POINT));

    Output(pt_arr, sizeof(pt_arr)/sizeof(POINT));
}

 

 

 

经验证成功!