import edu.gwu.algtest.*; import edu.gwu.util.*; /** * BubbleSort: implements the standard Bubble-Sort algorithm. * * High-level pseudocode: (for integer case) * Input: an array of integers. * // Key idea: Bubble smallest element, then next smallest etc. * * 1. For positions 0,...,length-1, find the element. * 1.1 Scan all elements past i starting from the end. * 1.1.1 If a pair of consecutive elements is out of * order, swap the elements. * * Output: same array, sorted. */ public class BubbleSort implements SortingAlgorithm { public void sortInPlace (int[] data) { // Key idea: Bubble smallest element, then next smallest etc. // 1. For positions 0,...,length-1, find the element for (int i=0; i < data.length-1; i++){ // 1.1 Scan all elements past i starting from the end: for (int j=data.length-1; j > i; j--) { // 1.1.1 If a pair of consecutive elements is out of // order, swap the elements: if (data[j-1] > data[j]) swap (data, j-1, j); } } } public void sortInPlace (Comparable[] data) { for (int i=0; i < data.length-1; i++){ for (int j=data.length-1; j > i; j--) { // Notice the use of the compareTo method: if (data[j-1].compareTo (data[j]) > 0) swap (data, j-1, j); } } } public int[] createSortIndex (int[] data) { // 1. Create space for a sort index: int[] index = new int [data.length]; // 2. Initialize to current data: for (int i=0; i i; j--) { if (data[index[j-1]] > data[index[j]]) swap (index, j-1, j); } } return index; } public int[] createSortIndex (Comparable[] data) { int[] index = new int [data.length]; for (int i=0; i i; j--) { if (data[index[j-1]].compareTo (data[index[j]]) > 0) swap (index, j-1, j); } } return index; } void swap (int[] data, int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } void swap (Comparable[] data, int i, int j) { Comparable temp = data[i]; data[i] = data[j]; data[j] = temp; } ////////////////////////////////////////////////////////////////////// // SortingAlgorithm interface. public String getName () { return "BubbleSort"; } public void setPropertyExtractor (int algID, PropertyExtractor props) { } ////////////////////////////////////////////////////////////////////// // Testing. public static void main (String[] argv) { BubbleSort bSort = new BubbleSort (); int totalTests = 10; int dataSize = 100; int[] data = new int [dataSize]; for (int ntests=0; ntests < totalTests; ntests++) { // Create the data: for (int i=0; i < dataSize; i++) data[i] = (int) UniformRandom.uniform ( (int) 1000, (int) 10000); // Sort: bSort.sortInPlace (data); // Check: boolean ok = true; for (int i=0; i < dataSize-1; i++) if (data[i] > data[i+1]) ok = false; if (! ok) { System.out.println ("Failure detected for test#" + ntests); System.exit (0); } } System.out.println ("Passed"); } }