Bubble Sort
/**********************************************************************************************************************************************
Arrays passed by reference, elements passed by value.
If just pass the elements
to be swapped by value, then the calling method cannot be aware of the changes.
The array, therefore, is also passed. Since it is passed by reference, changes
to its elements are known by the calling method.
**********************************************************************************************************************************************/
class Example
{
public static void main (String []args)
{
int array[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
bubbleSort( array );
//Calling bubbleSort and passsing array
}
public static void bubbleSort( int array2[] ) //bubbleSort
method, note different name
{
for ( int pass = 1; pass < array2.length; pass++ )
{
for ( int element = 0; element < array2.length - 1; element++ )
{
if ( array2[ element ] > array2[ element + 1 ] )
swap( array2, element, element + 1 );
}
}
}
//The swap method
public static void swap( int array3[], int first, int second )
{
int hold;
hold = array3[ first ];
array3[ first ] = array3[ second ];
array3[ second ] = hold;
}
}