我正在尝试进行冒泡排序,根据字符串“desc”按升序改变几个并行数组的位置。当我运行程序时,我只是得到一个空白屏幕,程序永远不会完成。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
const int maxp = 50;
void swap(string& a, string& b)
{
string temp;
temp = a;
a = b;
b = temp;
}
//These swapem functions are the functions used to move the array
//values when the sort function is called
void swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swap(char& a, char& b)
{
char temp;
temp = a;
a = b;
b = temp;
}
void swap(double& a, double& b)
{
double temp;
temp = a;
a = b;
b = temp;
}
void sort(int id[], string desc[], int numsold[], double price[],
double dolars[], int nump)
{
int i, j;
for (j = 0; j < nump - 1; j++)
for (i = 0; i = nump - 1; i++) //I'm sorting a group of parallel arrays by the
if (desc[i] > desc[i+1])//string "desc", and the others are being moved based off of that
{
swapem(desc[i], desc[i + 1]);
swapem(id[i], id[i + 1]);
swapem(numsold[i], numsold[i + 1]);
swapem(price[i], price[i + 1]);
swapem(dolars[i], dolars[i + 1]);
}
}
int main()
{
int id[maxp], numsold[maxp], nump;
double price[maxp], dolars[maxp];
string desc[maxp];
ifstream inf;
ofstream outf;
inf.open("storesales.dat");
outf.open("storesales.ot");
outf.setf(ios::fixed);
outf.precision(2);
initem(desc, id, numsold, nump, price, dolars);
readem(id,numsold,nump,price,desc);
printem(id, desc, numsold,nump, price, outf);
getsales(numsold, price, dolars,nump);
sortem(id, desc, numsold, price, dolars, nump);
printem(desc, id, numsold, nump, price, dolars, outf);
system("pause");
}
我知道这些功能是问题所在,因为我重新测试了它们并对调出进行了评论,程序结束了。问题是,我不知道出了什么问题。
答案 0 :(得分:1)
sortem()
中的禁止循环:
for (i = 0; i = nump - 1; i++)
应该是条件而不是赋值,即:
for (i = 0; i < nump - 1; i++)
预期for
循环的第二个参数condition
。分配i = nump
始终返回true
,从而无限循环。结果,你的空白屏幕。
答案 1 :(得分:1)
错误发生在第二个循环中
为获得最佳性能,您可以按如下方式进行内部循环:
for(i = j; i&lt; nump - 1; i ++)
答案 2 :(得分:1)
这已经回答了几个愚蠢的建议:
为什么您希望j
循环nump-1
次?
当嵌套循环中没有交换时你应该停止...这意味着在完成排序时停止。否则,您的排序将始终采用最坏情况运行时。
for (j=1;j;) // loop while j is set
for (j=0,i=0;i<nump-1;i++) // reset j
if (desc[i] > desc[i+1]) // if swap needed
{
swapem(desc[i], desc[i + 1]); // swap elements
swapem(id[i], id[i + 1]);
swapem(numsold[i], numsold[i + 1]);
swapem(price[i], price[i + 1]);
swapem(dolars[i], dolars[i + 1]);
j=1; // and set j so this loops until array is ordered
}
你也在使用具有其优点的并行数组,但我认为在你的情况下使用struct
或class
会更好地简化代码(特别是交换)有点单个数组里面的所有信息。