多点坐标排序算法

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

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

 

 

 

经验证成功!

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值