public class BubbleSort2 { void bubble (int[] data, int startingPosition) { // Swap down the element that belongs in "startingPosition". for (int j=data.length-1; j > startingPosition; j--) { if (data[j-1] > data[j]) swap (data, j-1, j); } } public void sortInPlace (int[] data) { // Key idea: Bubble smallest element, then next smallest etc. // 1. For positions 0,...,length-1, find the element that belongs there: for (int i=0; i < data.length-1; i++){ bubble (data, i); } } void swap (int[] data, int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } ////////////////////////////////////////////////////////////////////// // Testing. public static void main (String[] argv) { BubbleSort2 bSort = new BubbleSort2 (); 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"); } }