"bubble sort algorithm"小错误
The "bubble sort algorithm" small error
我被给予了:
"编写一个实现整数数组的气泡排序的函数。该函数的原型如下:void sort(int data [],int count);
编写一个提示文件名的程序,打开该文件并将数字从文件中读取到数组。然后,您的程序应调用您的排序例程,然后打印结果数组。"
我完成了它,它的工作正常,直到我被告知数字已经按秩序的情况下也必须尽早停止。您将在下面的void函数中看到这种尝试。我没有遇到任何错误;该程序编译,执行并关闭良好。现在的问题是添加了布尔变量,它不再分类数字。它将以与文本文件相同的顺序打印出它们。我通过调试器进行了运行,并注意到" II"变量并没有像应该(...; ...; ii )那样增加1个通行证,而是保持0。任何想法?<<
" integers.txt"文件中的(随机)数字:12 42 5 67 41 9 19 93 10 124 21
void sort(int data[], int count);
int main()
{
const int MAX_SIZE = 128;
char fileName[MAX_SIZE];
int data[MAX_SIZE];
int count = 0;
cout << "Enter a file name: "; //integers.txt
cin.clear();
cin.ignore(cin.rdbuf()->in_avail());
cin.getline(fileName, sizeof(fileName));
ifstream input(fileName); //opens the file and reads the first line
if (input.is_open())
{
while (!input.eof() && count <= MAX_SIZE) //adds data to the array until the end of the file is reached
{
input >> data[count];
count += 1;
}
input.close();
}
else
{
cout << "nThe file failed to open, try again.n";
}
sort(data, count); //calls the bubble sort function
return 0;
}
void sort(int data[], int count)
{
int temp = 0;
int pass = 0;
bool sorted = false;
for (int pass = 0; pass <= count; pass += 1) //counts the number of passes
{
for (int ii = 0; (ii <= (count - pass - 1)) && (sorted = false) ; ii++) //sorts the integers from least to greatest
{ //also 'supposed to' stop early if already sorted
if (data[ii] > data[ii + 1])
{
sorted = false;
temp = data[ii];
data[ii] = data[ii + 1];
data[ii + 1] = temp;
}
}
}
cout << "nSorted integers: ";
for (int jj = 1; jj <= count; jj += 1) //prints the sorted integers
{
cout << data[jj] << " ";
}
cout << "nn";
}
您想在外循环中进行sorted
检查。那就是:
for (int pass = 0; pass < count && !sorted; pass += 1) //counts the number of passes
{
sorted = true;
for (int ii = 0; ii < (count - pass); ii++) //sorts the integers from least to greatest
{
这里的想法是,在每个通行证的开头,您假设数组是对的。如果进行交换,则可能不会对数组进行排序,因此将标志设置为false
。只有当您在没有任何交流的情况下进行整个通行证时,标志才会是正确的。
另外,请注意,我将您的外循环比较更改为pass < count
而不是pass <= count
。请记住,当您从0开始时,极限为 count-1
。
我还将内部循环条件从<= (count - pass - 1)
更改为< (count - pass)
。它们等效,但后者更简洁。
相关文章:
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- std::sort 导致运算符分段错误<
- 错误:"类 std::vector<Shape*>"没有名为"sort"的成员
- 为什么 leetcode c++ sort() 给出编译错误
- "bubble sort algorithm"小错误
- 为什么 std::sort 默认假定 std::vector< std::vector<int> >为 std::vector,从而产生错误的结果?
- 为什么当 std::sort 中的比较函数始终返回 true 时出现运行时错误
- 我的 C++11 测试表明 sort(vector<string>) 甚至比 C++03 慢,有什么错误吗?
- std :: sort函数上的编译器错误(GCC 4.4)
- 在 c++ 中使用 std::sort 时没有合适的转换错误
- VS 到 CBlocks, std::sort, operator< 编译器错误
- std::sort - 正在传递错误的比较器未定义的行为
- std::list.sort(谓词)编译器错误
- Merge Sort C++实现,无法识别代码中的错误
- sort对某些值排序错误
- 使用zip迭代器调用boost::compute::sort()会导致构建错误
- 在 std::sort() 中的自定义函数中,>(大于)运算符与 <(小于运算符)的交换会导致分段错误吗?
- 为什么sort()函数用于一组类对象时会导致编译错误
- 使用std::sort比较器函数时出现异常错误
- 为什么std::sort会在这段代码上抛出分段错误?