A question on Bubble Sort

I compiled the following code:

#include<stdio.h>
int main()
{

int c=0, d=0, i, j, k, n, choice, swap, arr[20];

char str[20][20], temp[20];

clrscr();

printf(“Enter selection: 1(string(s)) or 2(numbers)\n”);

scanf("%d", &choice);

switch(choice)
{
case 1:
puts(“Enter the no. of string(s) to be sorted”);
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0) //compares the strings
{
strcpy(temp,str[i]); //swapping is done if
strcpy(str[i],str[j]); //first string is
strcpy(str[j],temp); //greater than second string
d++;
}
}
}
if(d>0)
{
printf(“The sorted list:\n”);
for(i=1;i<=n;i++)
printf("%s\n", str[i]);
}
else if(d==0)
{
printf(“The list is pre-sorted.”);
}
break;

case 2:
printf("Enter n:\n");
scanf("%d", &n);
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
for(i=0;i<n;i++)
{
	for(j=i+1;j<n;j++)
	{
		if(arr[i]>arr[j])
		{
			swap=arr[i];
			arr[i]=arr[j];
			arr[j]=swap;
				printf("%d ", arr[i]);
				printf("\n");
			c++;
		}
	}
}
if(c>0)
{
	printf("The sorted list:\n");
	for(i=0;i<n;i++)
		printf("%d\n", arr[i]);
}
else if(c==0)
{
	printf("The list is pre-sorted.");
}

}
getch();
return 0;
}

Consider case 2 only.
Now I need to also print the intermediary steps of this bubble-sort algorithm.
Example:
Let the unsorted list be:
4 2 1 3
Then steps include:
Since 4>2 then the list shall be
2 4 1 3 until 2 1 3 4 in Pass 1 and until 1 2 3 4

What can I do?
Please help.

In the if condition inside, after swapping, put this loop:

if(){
for(i=0;i<n;i++)
  cout<<arr[i]<<" ";
}// if ends here
cout<<endl; // will help in distinguishing the next iteration.

See this or the below code for the working implementation of mine,

for(i=n-1;i>=0;i--)
{
	for(j=0;j<=(i-1);j++)
	{
		if(a[j]>a[j+1])
		{
			temp= a[j];
			a[j]=a[j+1];
			a[j+1]=temp;
			
			cout<<"Inside : ";
			for(int k=0;k<n;k++)  // printing intermediate steps
			cout<<a[k]<<" ";
			
			cout<<endl;
		}
	}
}

for(i=0;i<n;i++)
 cout<<a[i]<<" ";    

@damn_me
Worked like a charm.
Thank you so much.

1 Like

@shubhgoyal Happy to help… :slight_smile: