Question: The bubble sort algorithm is less efcient than it could be. If a pass is made through the list without exchanging any elements, this means

The bubble sort algorithm is less efcient than it could be. If a pass is made through the list without exchanging 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.

the code is given needs to be modified:

public class Sorting { public static > void selectionSort(T[] data) { int min; T temp; for (int index = 0; index < data.length-1; index++) { min = index; for(int scan = index + 1; scan < data.length; scan++) if(data[scan].compareTo(data[min]) < 0) min = scan; swap(data, min, index); } } public static > void swap(T[] data, int index1, int index2) { T temp = data[index1]; data[index1] = data[index2]; data[index2] = temp; } public static > void insertionSort(T[] data) { for (int index = 1; index < data.length; index++) { T key = data[index]; int position = index; while(position > 0 && data[position-1].compareTo(key) > 0) { data[position] = data[position-1]; position --; } data[position] = key; } } public static > void bubbleSort(T[] data) { int position, scan; T temp; for(position = 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); } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!