Q. The reason bubble sort algorithm is inefficient is that it continues execution even after an array is sorted by performing unnecessary comparisons. Therefore, the number of comparisons in the best and worst cases both are same. Modify the algorithm such that it will not make the next pass when the array is already sorted.
Ans:
The bubble sort continues the execution even after an array is sorted. To avoid unnecessary comparisons we add a Boolean variable say switched and initialize it by True in the starting. Along with the "for" loop, we hear add the condition (switched=true) and make it false inside the outer for loop. If a swapping is done then the value of switched is made true. Thus if no swapping has been done in the first pass, then no more comparisons will be done further and the program shall exit.
The algorithm after modifying it in the above stated manner will be as follows:-
void bubble(int x[],int n)
{
int j,pass,hold;
bool switched=true;
for(pass=0;pass
{
switched=false;
for(j=0;j
{
switched=true; hold=x[j]; x[j]=x[j+1];
x[j+1]=hold;
}
}
}