/** * BubbleSort * * This class sorts an array by comparing neighboring elements. If the element * towards the end of the array is less than the previous element, than * we swap the two elements. Thus, the lighter elements in the array float towards * the front of the array. Hence, the name BubbleSort. * @author Brad Rippe * @version 1.0 */ public class BubbleSort { /** * BubbleSort's main */ public static void main(String[] args) { int[] exampleArray = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; bubbleSort(exampleArray); System.out.println("ExampleArray:"); for(int i = 0; i < exampleArray.length; i++) System.out.print(exampleArray[i] + ", "); } /** * This method sorts an array by increasing order. * bubbleSort uses pass by reference to modify the pass array. * @param array the array to be sorted */ public static void bubbleSort(int[] array) { for(int i = 0; i < array.length-1; i++) { for(int j = 0; j < array.length-1-i; j++) { if(array[j] > array[j+1]) swap(array, j); } } } /** * This method swaps changes the position of two elements * based on the starting index. Swap changes the elements * at the starting index and the starting index plus 1. * This method can only be used by the BubbleSort class. * All other class don't have access to this method because * of the keyword "private" in the definition. * @param array the array where the elements are to be swapped * @param startIndex the index of the first element to be swapped */ private static void swap(int[] array, int startIndex) { int tempInt = array[startIndex]; array[startIndex] = array[startIndex+1]; array[startIndex+1] = tempInt; } }