【发布时间】:2015-03-06 05:23:52
【问题描述】:
我的程序的任务是对用户给出的 x-y 平面上的点进行排序,根据它们与原点的距离使用桶排序。在具有相同距离的两个点的情况下,具有最小 x 坐标的点将被选为第一个点。如果距离和 x 坐标相同,则具有最小 y 坐标的元素将首先出现。输出是点本身,而不是它们的距离。到目前为止,我发现的最合乎逻辑的方法是创建一个自定义数据结构,其中包含 x 坐标、y 坐标及其距离在一个元素中。我目前遇到的问题是我当前的双打标准向量算法,我不知道如何转换排序以满足我的需要。任何想法或建议都会有所帮助。
这是结构的布局:
struct point {
double xc;
double yc;
double dist; };
当前的桶排序,适用于双精度向量。
void bucketSort(vector<double> &arr) {
int n = B.size();
vector<point> b[n];
for (int i=0; i<n; i++)
{
int bi = n*arr[i];
b[bi].push_back(arr[i]);
}
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
int index = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < b[i].size(); j++){
arr[index++] = b[i][j]; }
}
}
截至目前的全部代码。
using namespace std;
struct point {
double xc;
double yc;
double dist;
};
vector<double> A;
vector<double> B;
double findDistance(double x = 0, double y = 0) {
double x2 = pow(x, 2);
double y2 = pow(y, 2);
double z = x2 + y2;
double final = sqrt(z);
return final;
}
void bucketSort(vector<double> &arr)
{
int n = B.size();
vector<point> b[n];
for (int i=0; i<n; i++)
{
int bi = n*arr[i];
b[bi].push_back(arr[i]);
}
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
int index = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < b[i].size(); j++){
arr[index++] = b[i][j]; }
}
}
int main(){
double number; int t = 0;
while (cin >> number){
A.push_back(number); }
struct point C[A.size()];
while (t < A.size()){
C[t / 2].xc = A[t]; C[t / 2].yc = A[t + 1];
C[t / 2].dist = (findDistance(A[t], A[t + 1])); t += 2; }
cout << setprecision(6); cout << fixed; ;
bucketSort(C);
cout << showpos; cout << fixed;
int x = 0;
while (x < (A.size() / 2)){
cout << C[x].xc << " " << C[x].yc << endl;
x++;
}
}
一个双精度向量 B 在这里,因为最初,我试图用多个双精度向量来完成它。
这是输入的示例:
0.2 0.38
0.6516 -0.1
-0.3 0.41
-0.38 0.2
示例输出:
-0.380000 +0.200000
+0.200000 +0.380000
-0.300000 +0.410000
+0.651600 -0.100000
我意识到这一点可以添加更多功能以使其更易于使用,但我的目标是获得当前的工作。任何建议或帮助将不胜感激。请和谢谢。
【问题讨论】:
-
是的,我的错。添加了标签。
标签: c++ data-structures c++14 bucket-sort