这个冒泡排序代码有什么错误?
What is the error in this bubble sort code?
我为冒泡排序编写了这个简单的代码,但它给出了一些随机垃圾值作为输出。有人可以告诉我我的错误吗?我尝试在函数 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;
}
for(i=0;i<size;i++);
末尾的分号不属于那里。这会导致未定义的行为。
最终结果是这个函数在数组结束后打印了一个垃圾值。
我为冒泡排序编写了这个简单的代码,但它给出了一些随机垃圾值作为输出。有人可以告诉我我的错误吗?我尝试在函数 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;
}
for(i=0;i<size;i++);
末尾的分号不属于那里。这会导致未定义的行为。
最终结果是这个函数在数组结束后打印了一个垃圾值。