// BubbleSort.java
// Sorts array in ascending order using a bubble sort
// APPLET CODE="BubbleSort" HEIGHT=150 WIDTH=300
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BubbleSort extends JApplet implements ActionListener {
        // declare and hard code the array
        int p[ ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
        int temp;  // temporary holding area for swap

        // GUI Components
        Container c;
        JTextArea outputArea;
        JButton b;

        public void init( ) {
                c = getContentPane( );
                c.setLayout( new FlowLayout( ) );
                outputArea = new JTextArea( 6, 20 );
                c.add( outputArea );
                b = new JButton( "Sort" );
                b.addActionListener( this );
                c.add( b );
        }

        public void actionPerformed( ActionEvent e ) {
                outputArea.append( "Data items in original order: \n" );
                for ( int i = 0; i < p.length; i++ )
                        outputArea.append( " " + p[ i ] );
                
                sort(  );  // no need to pass array since it's an instance variable
                outputArea.append( "\nData items in ascending order: \n" );

                for ( int i = 0; i < p.length; i++ )
                        outputArea.append( " " + p[ i ] );
        }

        void sort( ) {
                for ( int pass = 1; pass < p.length; pass++ )
                        for ( int i = 0; i < p.length - pass; i++ )
                                if ( p[ i ] > p[ i + 1 ] ) {
                                        temp = p[ i ];
                                        p[ i ] = p[ i + 1 ];
                                        p[ i + 1 ] = temp;
                                }
        }
}