Bubble Sorting Code

CODE:
#include
using namespace std;
void bubblesort(int a[],int n){
for(int i=0;i<n;++i)
{ cout<<endl;
for(int j=0;j<n-i;++j)
{
if(a[j]>a[j+1])
swap(a[j],a[j+1]);

}

for(int i=0;i<5;++i)
cout<<a[i]<<" “;
}
}
int main()
{
int a[5]={637,937,64,20,748};
bubblesort(a,5);
for(int i=0;i<5;++i)
cout<<a[i]<<” ";
return 0;
}

PROBLEM ENCOUNTERED: The value 937 is getting converted to 0.

NOTE: I used cout in the function to see what was happening at every step.

Hello @poojagera,

The reason for the incorrect answer is invalid index.
for i=0 and j=n-1 (both are valid index)
j+1 = n (invalid index)
It might be possible that a[n] contains 0.
So, 0 being smaller to 937.
swapping is being done.
Hence, leading to an incorrect answer.

Solution:

  1. for(int i=0;i<n-1;++i)
  2. for(int j=0;j<n-1-i;++j)

Hope, this will help.
Give a like if you are satisfied.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like