The bubble sort algorithm shown in this chapter is less efficient than it could
ID: 642562 • Letter: T
Question
The bubble sort algorithm shown in this chapter is less efficient than it could be. If a pass is made through the list without ex- changing any elements, this means that the list is sorted and there is no reason to continue. Modify this algorithm so that it will stop as soon as it recognizes that the list is sorted. Do not use a break statement! Make it to where it compiles succesfully. Thanks
Program:
public static>
voide bubbleSort(T[] data)
{
int position, scan;
T temp;
for (posistion=data.length -1; position>=0; position--)
{
for (scan=0; scan <= position -1;scan++)
{
if (data[scan].compareTo(data[scan+1])>0)
swap(data,scan,scan+1);
}
}
}
Please Explain with //notes
Explanation / Answer
The following code is fulfill your requirement plz check it.
voide bubbleSort(T[] data)
{
int position, scan,p=-1;
T temp;
for (posistion=0; position<=data.length -1; position++)
{
if(p+1==position)
{
for (scan=0; scan <= position -1;scan++)
{
if (data[scan].compareTo(data[scan+1])>0)
{
swap(data,scan,scan+1);
p=position;
}
}
}
else
{
printf("List is sorted");
exit(0);
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.