package Examples; import java.util.*; /** * Performs a bi-directional bubble sort on "list", also known as a * cocktail sort. After making bubbling from left to right, the * algorithm then bubbles from right to left. There is a subtle error * injected that causes the first element to be ignored. * */ @Sequenic.T2.T2annotation.option("--elemty=java.lang.Integer") public class CocktailSort { private Comparable[] list; /** * The working function for Sort. */ private void cocktail_sort() { // INJECTING ERROR, beg should be initialized to 0: int beg = 1; //Beginning index for the left-to-right pass int end = list.length - 1; //End index for the left-to-right pass Comparable tmp = null; //Temporary variable for swapping boolean hasSwapped = false; //Denotes whether a swap was made during a pass // main loop: do { hasSwapped = false; //Bubble sort from left-to-right starting at beg and ending at end for (int i = beg; i < end; ++i) { if (list[i].compareTo(list[i + 1]) > 0) { tmp = list[i]; list[i] = list[i + 1]; list[i + 1] = tmp; hasSwapped = true; } } --end; //Decrease end by one //Bubble sort from right-to-left starting at end and ending at beg for (int i = end; i > beg; --i) { if (list[i].compareTo(list[i - 1]) < 0) { tmp = list[i]; list[i] = list[i - 1]; list[i - 1] = tmp; hasSwapped = true; } } ++beg; //Increment beg by one } while ((hasSwapped == true) && (beg != end)); //While no swaps have been made } /** * Sort the given array. */ public Comparable[] Sort(Comparable[] unsorted) { // Initializes list to the passed unsorted list, and then // invokes the cocktail sort algorithm on that list. The // resulting sorted list will then be returned. list = unsorted; cocktail_sort(); return list; } /** * The specification of Sort. */ public Comparable[] Sort_spec(Comparable[] unsorted) { assert unsorted != null : "PRE" ; Comparable[] r = Sort(unsorted); boolean ok = true; for (int i = 0; i < list.length - 1 && ok; i++) { ok = list[i].compareTo(list[i + 1]) <= 0; } assert ok : "POST"; return r; } /** * This one will sort a list; the result is put in an array. */ public Comparable[] Sort(List unsorted) { Comparable[] array = new Comparable[unsorted.size()]; for (int i = 0; i < unsorted.size(); i++) { array[i] = unsorted.get(i); } return Sort(array); } /** * The spec. of Sort on List. */ public Comparable[] Sort_spec(List unsorted) { assert unsorted != null : "PRE" ; Comparable[] r = Sort(unsorted); boolean ok = true; for (int i = 0; i < list.length - 1 && ok; i++) { ok = list[i].compareTo(list[i + 1]) <= 0; } assert ok : "POST"; return r; } static public void main(String[] args) { // Calling T2 from here; see how it finds the mistake: Sequenic.T2.Main.main(CocktailSort.class.getName()); } }