【发布时间】:2019-04-30 15:20:48
【问题描述】:
当我调用我的打印函数时,我的程序会在我通过冒泡排序后显示未排序的数据。我已将我的代码与朋友和我在 geeksforgeeks (https://www.geeksforgeeks.org/bubble-sort/) 上找到的关于冒泡排序的文章进行了比较,无论出于何种原因,我的数据都不会排序。
我正在为我的大学数据结构课程编写一个具有 4 个排序功能的程序。理论上应该发生的是程序读取包含 8000 个随机数的数据文件,并根据调用的排序(冒泡排序、插入排序、选择排序和快速排序)对数据进行排序。调用打印函数并将显示每 1000 个数据元素以显示数据确实已排序。我尝试在 main 中编写我的打印代码,将打印调用放入排序函数中,并使用函数进行打印,Quadruple 检查了我的排序函数。我也尝试过不同的编译器和不同的计算机,但我怀疑我的代码有些古怪。
原码:
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
const int arraysize = 8000;
int numcompares, numcopies;
void swapem(double a, double b)
{
double temp;
temp = a;
a = b;
b = temp;
}
void bubblesort(double r[], int n)
{
int j, i;
for (j = 0; j < n - 1; j++)
{
for (i = 0; i < n - 1; i++)
{
numcompares++;
if (r[i] > r[i + 1])
{
swapem(r[i], r[i + 1]);
numcopies += 3;
}
}
}
}
void printem(double r[])
{
cout << r[1000] << ", " << r[2000] << ", " << r[3000] << ", " <<
r[4000] << ", " << r[5000] << ", " << r[6000] << ", " << r[7000] << ", " << r[7999] << endl;
}
int main()
{
ifstream inf("data.dat");
ofstream outf("sorted.ot");
string sortname;
double arraynums[arraysize];
for (int i = 0; i < arraysize; i++)
{
inf >> arraynums[i];
}
bubblesort(arraynums, arraysize);
system("pause");
return 0;
}
我试过了:
void printem(double r[], int n)
{
int i;
for (i = 0; i < n; i++)
cout << r[i]<< ", ";
}
printem(arraynums,20); // in main
和主要
for (int i = 0; i < 10; i++)
{
cout << arraynums[i] << endl;
}
这是拒绝排序的 8000 个随机整数中的 10 个
41275.4
12113.1
50676
7662.34
50688.3
-7926.28
13672.8
-3212.9
-13046.5
-16798
输出应该是: -16798 -13046.5 -7926.28 -3212.9 7662.34 12113.1 13672.8 41275.4 50676 50688.3
但它仍保持未排序的形式: 41275.4 12113.1 50676 7662.34 50688.3 -7926.28 13672.8 -3212.9 -13046.5 -16798
【问题讨论】:
-
您可能想单独测试
swapem函数。 -
欢迎来到 Stack Overflow。你熟悉引用传递和值传递的区别吗?