【发布时间】: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