2014-09-28 38 views
-2

我有一個任務,用三個維度對點進行排序,然後在屏幕上顯示它們。他們與空間分開。有沒有比我更快的方法?排序3d點

我可以如何把它放在三維數組中,並做一些排序功能?

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

'if(x [j] == x [j + 1])'(在下一個測試中相同)對您的輸入可能不是真的。 – usr2564301 2014-09-28 12:17:31

回答

9

此問題有一個C++ -Tag。 struct,std::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; 
    } 
} 
2

是的,有比你的方法更快的方法。具體而言,您使用插入排序來進行排序算法。更快的算法是Mergesort或Quicksort。

更快的方法是使用二維數組,然後使用自定義比較函數提供庫排序方法。這將使您的代碼更易於閱讀並利用sort()中的優化。