【问题标题】:Ordering of coordinates坐标排序
【发布时间】:2012-03-24 20:43:01
【问题描述】:

假设我有n

(x,y1),(x2,y2),.....(xn,yn)

我的目标是以这样的方式连接这些点,我得到一个没有自相交的样条线。我的方法是通过增加 x 值的顺序来对这些元素进行排序,如果它们相等,则比较 y 值。这是我的方法:

#include<iostream>
#include<ctime>

using namespace std;
#define N  1000
struct  Point
{
    int x;
    int y;

}point[N];
int main()
{
    int start=clock();
    int n;
    cout<<" enter  number of coordinantes " <<endl;
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>point[i].x>>point[i].y;

    for(int i=1;i<=n-1;i++){
        for(int j=i+1;j<=n;j++)
        {
            if(point[i].x>point[j].x)
            {
                int t=point[i].x;
                point[i].x=point[j].x;
                point[j].x=t;

            }
            if( point[i].x==point[j].x)
            {

                if(point[i].y>point[j].y)
                {
                    int s=point[i].y;
                    point[i].y=point[j].y;
                    point[j].y=s;
                }
                }


            }

    }
    int end=clock();
    cout<<"coordinantes are :"<<endl;
    for(int i=1;i<=n;i++)
        cout<<point[i].x<<" "<<point[i].y<<endl;
    cout<<(end-start)/(float)CLOCKS_PER_SEC<<endl;
    return 0;
}

当我输入的元素数量等于 20 时,花费了 102.59 毫秒(笔记本电脑具有 2.5 RAM,1.87 GH)。我的方法是最优的还是存在更好的方法?

【问题讨论】:

标签: c++ algorithm geometry complexity-theory


【解决方案1】:

您算法中的瓶颈是排序 - 即O(n^2)。可以在 O(nlogn) 中完成 - 渐进性要好得多。

您应该首先使用更快的排序方式对数据进行排序,然后在调用算法第二阶段的元素上进行迭代。

还请注意,从设计上讲 - 通常在程序的各个部分之间分开是一种很好的做法 - 在您的情况下 - 在排序和后面的部分之间分开遍历。

对于排序,你可能想看看std::sort(),你可能想熟悉quicksort

【讨论】:

    【解决方案2】:

    如果您担心性能,我会指出以下几点:

    1) 您正在使用 1000 个元素 - 内存浪费。 使用 *point & do malloc 获取所需数量的元素。

    2) 您当前的实现中没有使用 point[0] - 内存浪费! ;-)

    3) 正如其他人所说,您的排序算法不是最佳选择。

    当我输入元素 20 的数量时,花了 102.59 毫秒(笔记本电脑 2.5 RAM,1.87 GH),所以这是最佳方式

    处理 20 个元素并不能说明算法的效率。样本需要足够大以合理地对程序进行基准测试。

    【讨论】:

      【解决方案3】:

      继续排序,您可以按照自己的比较标准进行排序。

      boolean compare(Point A, Point B) {
         return ((A.x > B.x)||((A.x==B.x)&&(A.y>B.y)));
      }
      

      (为语法道歉...我的 C++ 生锈了)

      然后你使用一个很好实现的算法来执行排序,比如 std::sort 和这个函数作为比较顺序。

      【讨论】:

        猜你喜欢
        • 2021-10-06
        • 2011-11-05
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        • 2023-02-02
        • 2022-01-12
        • 2012-06-02
        • 1970-01-01
        相关资源
        最近更新 更多