Reputation: 37
I am trying to study for a test and one of the study questions I can't get deals with BubbleSort. The question is:
Modify the BubbleSort code below to short circuit its execution. By that I mean, modify it so that if a pass is completed without making any swaps, execution will stop.
public static<T extends Comparable<T>> 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 the values*/
temp = data[scan];
data[scan] = data[scan+1];
data[scan + 1] = temp;
}
}
}
}
Upvotes: 2
Views: 622
Reputation: 48610
You would need a boolean flag or a state.
A quick google search would have saved you the trouble: http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
repeat
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Upvotes: 2