Question & Answer: In class we discussed the bubble sort algorithm for sorting numbers into ascending order. It was said that t…..

In class we discussed the bubble sort algorithm for sorting numbers into ascending order. It was said that the bubble sort was highly inefficient. For each pass through the algorithm we had to do n-1 comparisons. The simplest way to improve its efficiency is to note at the end of the first pass the highest number is guaranteed to be in the last positon, so that in the next pass through the sort we only have to do n-2 comparisons. Similarly, after the second pass the second highest number is guaranteed to be in the second to last position, so in the 3rd pass we only have to do n-3 comparisons, etc. Modify the pseudocode to reflect this improvement. Write a program that asks for 6 integers and then performs this modified bubble sort on them, printing out the modified order after each cycle of sorts.

Expert Answer

 

#include <stdio.h>
#define SIZE 6

int arry[SIZE];

void printArray()
{
for (int i=0; i < SIZE; i++)
printf(“%d “, arry[i]);
printf(“n”);
}

// Modified bubble sort version
void bubbleSort()
{
int i, j;
bool isSwap;
int temp;
for (i = 0; i < SIZE-1; i++)
{
isSwap = false;
for (j = 0; j < SIZE-i-1; j++)
{
if (arry[j] > arry[j+1])
{
temp=arry[j];
arry[j]=arry[j+1];
arry[j+1]=temp;
isSwap = true;
}
}

printf(“Modified order after cycle %d: n”,i+1);
printArray();
// IF no two elements were swapped by inner loop, then break
if (isSwap == false)
break;
}
}

int main()
{

printf(“Please enter 6 integers for Bubble sort n”);
for (int i = 0; i < 6; i++)
{
scanf(“%d”, &arry[i]);
}

bubbleSort();
return 0;
}

OUTPUT:

Please enter 6 integers for Bubble sort
10 30 5 40 50 20
Modified order after cycle 1:
10 5 30 40 20 50
Modified order after cycle 2:
5 10 30 20 40 50
Modified order after cycle 3:
5 10 20 30 40 50
Modified order after cycle 4:
5 10 20 30 40 50

Still stressed from student homework?
Get quality assistance from academic writers!