【问题标题】:What is the error in this bubble sort code?这个冒泡排序代码有什么错误?
【发布时间】:2019-09-11 00:25:41
【问题描述】:

我为冒泡排序编写了这个简单的代码,但它给出了一些随机垃圾值作为输出。有人可以告诉我我的错误。我尝试在函数bubbleSort 中打印A[i]A[j] 的输出,看起来工作正常。但是为什么printSortedArray 没有给出正确的输出呢?谢谢!

#include <iostream>

using namespace std;

void swap(int *a, int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}
void printSortedArray(int A[],int size)
{
    cout<<"the sorted array is"<<endl;
    int i;
    for(i=0;i<size;i++);
    {
        cout<<A[i]<<" ";
    }
}
void bubbleSort(int A[],int size)
{
    int i,j;
    for(i=0;i<size;i++)
    {
        for(j=0;j<size-1-i;j++)
        {
            if(A[j]>A[j+1])
            {
                swap(A[j],A[j+1]);
            }
        }
    }
}

int main()
{
    int A[50]; int size,i;
    cout<<"enter the size of the array: ";
    cin>>size;
    cout<<"Enter the "<<size<<" numbers to be sorted"<<endl;
    for(i=0;i<size;i++)
    {
       cin>>A[i];
    }

    bubbleSort(A,size);
    printSortedArray(A,size);

    return 0;
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。你给它什么数据?导致错误的最小数组是什么?
  • 任何数据。即使我输入一个大小为 2 的数组,如果给出随机输出。例如,当我输入这两个值 4、2 时,输出为 13110352。它只是在不同的输入上生成一些随机数。
  • 你应该在开始编写排序函数之前测试过输出函数。
  • 请注意,您实际上是在调用标准库 std::swap 函数,该函数接受引用,而不是您自己的 swap 函数接受指针。
  • 哦,是的。我没看到。谢谢亚历克斯。

标签: c++ bubble-sort


【解决方案1】:
for(i=0;i<size;i++);

结尾的分号不属于那里。这会导致未定义的行为。

最终结果是这个函数在数组末尾打印了一个垃圾值。

【讨论】:

    猜你喜欢
    • 2022-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多