package com.mindprod.example;
import static java.lang.System.*;
/**
* Sort an array using a primitive Bubblesort.
* <p/>
* This algorithm is very slow when the number of elements to sort is large.
* It is just for learning purposes, not a production sort.
* Its saving grace is it is simple to code.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2010-12-28
* @since 2010-12-28
*/
public final class BubbleSort
{
/**
* Sort an array in place using a BubbleSort algorithm.
*
* @param a an array of integers, unsorted
*/
private static void sort( int a[] )
{
for ( int i = a.length; --i >= 0; )
{
boolean flipped = false;
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;
flipped = true;
}
}
if ( !flipped )
{
return;
}
}
}
/**
* test driver
*
* @param args not used
*/
public static void main( String[] args )
{
int[] a = { 9, 7, 8, 5, 4 };
sort( a );
for ( int elt : a )
{
out.println( elt );
}
}
}