排序3d点

时间:2014-09-28 11:57:18

标签: c++ arrays sorting

我有一个任务是用三维对点进行排序,然后在屏幕上显示它们。它们用空格隔开。有没有比我更快的方式?

我可以把它放在三维数组中并做一些排序函数吗?

#include <iostream>
using namespace std;
int x[1001], y[1001], z[1001];
int main()
{
int t;  // how many points
cin>>t;
for(int counter=0; counter<t; counter++)
{
    cin>>x[counter]>>y[counter]>>z[counter];
}

//sorting

for(int i=0; i<t; i++)
{
    for(int j=0; j<t; j++)
    {
        if(x[j]>=x[j+1])
        {
            int tx, ty, tz;
            tx=x[j];
            x[j]=x[j+1];
            x[j+1]=tx;
            ty=y[j];
            y[j]=y[j+1];
            y[j+1]=ty;
            tz=z[j];
            z[j]=z[j+1];
            z[j+1]=tz;
        }
        if(x[j]==x[j+1])
        {
            if(y[j]>=y[j+1])
            {
                int ty, tz;
                ty=y[j];
                y[j]=y[j+1];
                y[j+1]=ty;
                tz=z[j];
                z[j]=z[j+1];
                z[j+1]=tz;
            }
        }
        if(x[j]==x[j+1] && y[j]==y[j+1])
        {
            if(z[j]>=z[j+1])
            {
                int tz;
                tz=z[j];
                z[j]=z[j+1];
                z[j+1]=tz;
            }
        }
    }
}

//showing results
for(int counter=1; counter<=t; ++counter)
{
    cout<<x[counter]<<" "<<y[counter]<<" "<<z[counter]<<endl;
}
}

2 个答案:

答案 0 :(得分:9)

此问题有一个C++ - 标记。 structstd::vectorstd::sort可读/简单且快速。

struct Point {
     int x;
     int y;
     int z;
     Point() {}
     Point(int x, int y, int z) : x(x), y(y), z(z) {}

     bool operator<(const Point &o) const {
         if (x != o.x) {
             return x < o.x;
         }
         if (y != o.y) {
             return y < o.y;
         }   
         return z < o.z;
     }
};

#include <iostream>
#include <algorithm>

std::vector<Point> points;

int main() {
    int t;  // how many points
    std::cin >> t;
    points.reserve(t);
    for(int counter = 0; counter < t; counter++) {
        int x, y, z;
        std::cin >> x >> y >> z;
        points.push_back(Point(x, y, z));
    }

    std::sort(points.begin(), points.end());

    for(int counter = 0; counter < t; ++counter) {
        std::cout << points[counter].x << " "
                  << points[counter].y << " "
                  << points[counter].z << std::endl;
    }
}

答案 1 :(得分:2)

是的,有比你的方法更快的方法。具体来说,您正在使用Insertion Sort进行排序算法。更快的算法是Mergesort或Quicksort。

更快仍然是使用2D数组,然后使用自定义比较函数提供库排序方法。这将使您的代码更易于阅读并利用sort()中的优化。