Error in Bubble Sort code

Hi! can anybody please tell me whats wrong with my bubble sort C++ code. It gives some random garbage values as output.

#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;
}

First thing: Turn on compiler warnings.

>g++ -Wall main.cpp -o main
main.cpp: In function 'void printSortedArray(int*, int)':
main.cpp:18:2: warning: this 'for' clause does not guard... [-Wmisleading-indentation]
  for(i=0;i<size;i++);
  ^~~
main.cpp:19:2: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'for'
  {
  ^


Second thing: You have a semi-colon after your for loop line in printedSortedArray, making your loop not actually be a loop.

Third thing: You are not actually calling your swap function. You're calling std::swap(int&, int&), which is the standard library's swap function, which happened to be internally accessible within <iostream>. This only works by coincidence, and is one reason why "using namespace std;" can be a bad idea if you don't know what you're doing.

I would rename your swap function to something else or put it in its own namespace.
Or just get rid of your swap function and #include <algorithm> to properly access std::swap.
Last edited on
> misleadingly indented as if it were guarded by the 'for'
don't indent your code, make the IDE do it for you
I don't know of an IDE that wouldn't indent by default after an opening brace... I'm not sure if IDE auto-formatting would help here.
Last edited on
Probably not since it is not really the brace that is the problem, but that errant semicolon. This is why you fix errors from the top down, the first "error" is the key "error".


this is what clang-format does for me
1
2
3
for(i=0;i<size;i++)
   ;
{
Topic archived. No new replies allowed.