/** * Matt Kretchmar * April 1, 2006 * BubbleSortProgram.java * This program uses bubble sort to order an array of integers from * smallest to biggest. */ import java.util.Scanner; class BubbleSortProgram { public static void main ( String args[] ) { int a[] = readArray(); printArray(a); bubbleSort(a); printArray(a); } /** * A method that creates and returns an array of integers. First the user * is prompted for the size of the array and then the entries for the * array. */ public static int [] readArray ( ) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter number of items for array: "); int num = keyboard.nextInt(); int array[] = new int[num]; for ( int i = 0; i < num; i++ ) { System.out.println("Enter item " + i ); array[i] = keyboard.nextInt(); } return array; } /** * A method to print the contents of an integer array on one line. */ public static void printArray ( int a[] ) { for ( int i = 0; i < a.length; i++ ) System.out.print(a[i] + " "); System.out.println(); } /** * A method to sort an array of integers via the bubble sort * algorithm. */ public static void bubbleSort ( int a[] ) { for (int i = a.length-1; i > 0; i-- ) { for ( int j = 0; j < i; j++ ) { if ( a[j] > a[j+1] ) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } }