Bubble Sort
The program below will sort an array of integers. The array is declared, initialized with the numbers 18, 75, 12, 53, 27, 33 and printed to the output screen. A bubble sort is then performed to sort the integers and every swap is displayed. Finally the sorted array is displayed.
Copy the following code into a
text editor and
save it as bubblesort.java.
class bubblesort {
public static void main (String args[]){
int [] numbers = { 18, 75, 12, 53, 27, 33};
int flag = 1;
int x;
int n = 0;
int temp;
System.out.println( "starting array");
for (x=0 ; x < numbers.length; x++)
System.out.println( numbers[x] +
" at location " + x);
do {
flag = 0;
n=n+1;
System.out.println( "starting pass # " + n);
for (x=0 ; x < numbers.length - n; x++)
{
if (numbers[x] > numbers[x+1])
{ System.out.println("Swapping "+ numbers[x] +
" and " + numbers[x+1] + " at location " + x);
temp = numbers[x];
numbers[x] = numbers[x+1];
numbers[x+1] = temp;
flag = 1;
}
}
} while (flag != 0);
for (x=0 ; x < numbers.length; x++)
System.out.println( numbers[x] +
" at location " + x);
}
}
|
Line 3 sets up an array of integers and initializes the array with the numbers 18, 75, 12, 53, 27, 33 A flag = 1 indicates a swap has been made The for loop covers all array indices from 0 to the length of the numbers array While flag is not = 0(swaps have been made) initialize the loop variables and.. Go through the array and If necessary swap any adjacent elements that are out of order and if a swap is made set the flag. ( the while loop needs to be repeated.) Finally print out the sorted array. |
After compiling this program run it by typing
java bubblesort
The output should resemble the following.
starting array 18 at location 0 75 at location 1 12 at location 2 53 at location 3 27 at location 4 33 at location 5 starting pass # 1 Swapping 75 and 12 at location 1 Swapping 75 and 53 at location 2 Swapping 75 and 27 at location 3 Swapping 75 and 33 at location 4 starting pass # 2 Swapping 18 and 12 at location 0 Swapping 53 and 27 at location 2 Swapping 53 and 33 at location 3 starting pass # 3 12 at location 0 18 at location 1 27 at location 2 33 at location 3 53 at location 4 75 at location 5
The initial array is printed, every swap is displayed and the final sorted array is then shown. The array can be set to any number and arrangement of elements by changing the declaration. There are no parameters needed but the numbers array declaration could be changed to accept command line parameters. Just remember that all command line parameters are strings. They must be changed to integers by using a line similar to the following.
numbers[x] = Integer.parseInt(args[x]);
The next section will conclude our
study of Java applications by demonstrating how to open and read
files using Java data streams.
Go to the next topic: Accessing Files