Tutorial: Initializing and sorting an Array
using a bubble sort


Authored by
Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com






To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following link or send this page to a friend.)
  • <html>
    <title>Example of a link </title>
    <body>
    <table border>
    <a href="http://sumtotalz.com/TotalAppsWorks/Structures/Arrays/Sum_Array.html">An Introduction to Array Initialializer List and bubble sort </a>
    </table>
    </body>
    </html>
  1. Java Table of contents
  2. 2nd Java Cup
  3. Pie Chart I
  4. Pie/Bar Chart IB
  5. Pie/Bar Chart II
  6. Pie/Bar Chart III
  7. A Basic Calculator
  8. Linked Lists
  9. Linked List II
  10. Linked List III
  11. Linked List IV
  12. Hardware Store I
  13. Hardware Store II
  14. Hardware Store III
  15. Client/Server
  16. Client/Server II
  17. Client/Server III
  18. Client/Server IV
  19. Multithreaded Client/Server
  20. Multithreaded Client/Server II
  21. Multithreaded Client/Server III
  22. Basic Calculator II
  23. Basic Calculator III

Objectives

After you finish this tutorial, you will understand:

  • The array data structure.
  • The use of arrays to store, sort and search lists and tables of values.
  • How to declare an array, initialize an array and refer to individual elements in am array.
  • How to pass an array to a method.
  • Some basic sorting techniques.
  • How to declare and manipulate multi-dimensional arrays.

Introduction to Arrays

What is an array? We all understand the concept of an array. If I say that you have a bookcase that has ten shelves and you can place one book on a shelf. We all understand this instruction. Furthermore, if I say once you place the first book on a shelf, the other nine books must be of the same type (i.e., dictionary, mystery, computer science, etc.), we all understand this instruction. If we all understand the above instructions, then we understand the concept of an array. A bookcase contains books. An array contains data. An array of size ten contains 10 pieces of data. This is just like our bookcase that contained ten books with one book per shelf. An array is an important data structure in any programming language. An array is a fixed-length structure that stores multiple values of the same data type (i.e., int, float, long, char, double, etc.). You can group values of the same type within arrays. You cannot mix data types. For instance, you cannot store data of type int and float in the same array of primitive data types. Arrays are supported directly by the Java programming language; there is no array class. If part of our instruction for placing the books on the shelf is that the books should be sorted, using a bubble sort, based on their titles. How would we handle this requirement? We will explore using the bubble sort in our example found below. Primitive arrays (not to be confused with the Array class) should be considered as:

  • Data structures - consisting of related data items of the same type
  • Static - remain the size once they are created
  • An array - a group of contiguous memory locations that all have the same name and type
    • Most variables occupy a single location. The name of that variable is a reference to a memory location where that value of that variable is stored. Consider the following example.

      Variables
      Primitive
      Declaration
      Primitive
      Description
      Array
      Declaration
      Array
      Description
      int a = 10 ;
       
             |    |
             | 10 |
        a -> +----+
        ^
           |   
      address of where 
      'a' is located in 
      memory 
      
      int ar[] = new int[5] ;
      ar[0] = 10 ;
       
             |    |    |    |    |    |
             | 10 |    |    |    |    |
       ar -> +----+----+----+----+----+
      ^ | address of where 'ar' is located in memory
      Figure 1: Variable locations


      You will note that the value of '10' is stored at the location referenced by 'a'. In other words, the letter 'a' does not contain the value of '10'. Your house address does not contain your possessions; it is the house at that location that contains your possessions. Also note that ar[0] refers to the first location of the array ar.
  • The first element in an array is referenced by subscript 0.
  • The position number in the square brackets is called a subscript
  • A subscript must be an integer or an integer expression
  • When an expression is used as a subscript, the expression is evaluated first
  • If the array name is ar, the length may be determined by
     
        int len = ar.length ;
     
  • Every array in Java knows its own length
  • The brackets that enclose the subscript are an operator in Java
    • An array reference may be reassigned to an array of a different size

Declaring and allocating arrays

    Arrays occupy space in memory. The programmer specifies the data type of the elements and uses the new operator to dynamically allocate the space required to hold the elements specified. Arrays are considered objects and all objects must be allocated with the new operator. For example, to allocate a ten_element array named ar

     
        int ar[] = new int[10];
    
    ---------------- or case 2 ---------------------
    
        int ar[];
        ar = new int[10];
    
    
    ---------------- or case 3 ---------------------
    
    int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
    The above list encased within the brackets 
    is called an initializer list. It initializes the
    array with the initial values and the size of the
    array equals the number of values in the list.
    Figure 2: Declarations and Allocations


    When arrays are allocated, the elements are automatically initialized to

    • Zero for the numeric primitive types variables.
    • false for boolean, or
    • null for references (any nonprimitive type).
    For examples of declarations, consider the following:
     
    
    1-  String b[] = new String[ 100 ], 
           s[] = new String [ 27 ];
    
    2-  double[] array1, array2;
    
    3-  double[] array1 = new double[ 10 ], 
                   array2 = new double[ 20 ];
     
  • Every element of a String is a reference to a String that has the value null by default

SumArray template

In the following table, we will show aS SumArray code template.

 
/** ************************************************************
 * SumArray.java demonstrates the basic concept of the
 * Cardlayout Manager, array initialization, and the bubble sort.
 *
 ***************************************************************/

public class SumArray extends JFrame
                      implements ActionListener {

   public SumArray()  {

   }


   public void actionPerformed( ActionEvent e )  {

   }

   public void bSort() {

   }

   public void bDesSort() {

   }

   public void swapAscDes( int c[], int first, int second )    {

   }

   public static void main( String args[] ) {

   }
} /****************** End of SumArray class ************************/  
 
Figure 3: SumArray template

SumArray code example

In the following figure, you will find the code for this example.

  
/** ************************************************************
 * SumArray.java demonstrates the basic concept of the
 * Cardlayout Manager.
 *  
 * Copyright (c) 2002-2009 Advanced Applications Total Applications Works.
 * (AATAW)  all Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Total Application works nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *
 *
 ***************************************************************/

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


/** ****************************************************************
 * The SumArray class demonstrates the basic concept of the
 * Cardlayout Manager. It is a progam that displays three panels
 * using the Cardlayout API and responds to pressing of one of three
 * buttons.
 *
 ******************************************************************/
public class SumArray extends JFrame
                      implements ActionListener {
   private CardLayout cardLayManager;
   private JLabel label1, label2, label2b,  label3 ;
   private JPanel pStack, card1, card2, card3, card3a, buttonPanel;
   private JButton bArray[] , bSWest , bSEast ;
   private String cardNames[] = { "First card", "Next card",
                              "Previous card", "Last card" };
   private int a[] = { 1, 92, 72, 45, 35, 16, 27,
                        38, 79, 100, 25, 55,
                          47, 89, 30,15, 95 } ;
   private int n2[] = new int[20] , n3[] = new int[20] ;
   private int total = 0 , ii , len ;
   private JTextArea outputArea, outputArea2 ;
   private Container c ;
   private String output = "";


   /** ****************************************************************
    * The SumArray constructor
    *  1- Creates the client area context
    *  2- Create JTextArea object
    *  3- Sums the elements in the array
    *  4- Outputs the number of elements and the sum of the elements  
    *     in the array
    *  5- Adds outputArea JTextArea to client context
    *  6- Create String object 
    *     - Add title and array elements
    *     - Add String object to outputArea2
    *  7- Create CardLayout object
    *  8- Creates JPanels
    *  9- Creates JLabels
    * 10- Adds JLabels to card1 and card2
    * 11- Creates and sets up JButtons for card3
    * 12- Add card1, card2 and card3 to master panel - pStack
    * 13- Create a button panel and set the layout manager
    *     to GridLayout manager
    * 14- Creates and sets up JButtons for button panel
    * 15- Add button  panel to the west section of the client area
    *      - Add ActionListeners to these JButtons
    * 16- Add pStack to the center of the client area context
    * 17- Add wPanel to the bottom/South part of the client area context
    * 18- Set Size
    * 19- Show the GUI
    *
    ******************************************************************/
   public SumArray()
   {
      super( "CardLayout - Array Sum" );

      c = getContentPane();

      outputArea  = new JTextArea( 11, 10 ) ;
      outputArea2 = new JTextArea( 15, 10 ) ;

      for ( ii = 0; ii < a.length; ii++ )
         total += a[ ii ];

      outputArea.setText( "Total of no. of array elements:      " + ii + "\n" +
       "Sum of array elements:               " + total );

      c.add( outputArea ) ;

      output += "          Array Listing\n" ;
      output += "Subscript \tValue \n" ;
      len =   a.length ;
      for ( int i = 0; i < len; i++ )
         output += i + "\t" + a[ i ] + "\n";
      outputArea2.setText( output ) ;

      cardLayManager = new CardLayout();

      // create the JPanels
      pStack = new JPanel();
      pStack.setLayout( cardLayManager );

      card1 = new JPanel(); // set up card1 and add it to pStack
      card2 = new JPanel(); // set up card2 and add it to pStack
      card3 = new JPanel(); // set up card3 and add it to pStack
      card3a = new JPanel();  


      // create the JLabels
      label1  = new JLabel( "First card", SwingConstants.LEFT );
      label2  = new JLabel( "Second card", SwingConstants.LEFT );
      label3  = new JLabel( "Third card" );

      card1.add( label1 );
      card1.add( outputArea );

      card2.setBackground( Color.white );
      card2.add( label2 ) ;
      card2.add( outputArea2 );
 
      // set up card3 and add it to JPanel deck
      card3.setLayout( new BorderLayout() );
      card3.add( new JButton( "North" ), BorderLayout.NORTH );
      card3.add( bSWest = new JButton( "West Sort" ), BorderLayout.WEST );
      card3.add( bSEast = new JButton( "East Sort" ), BorderLayout.EAST );
      card3.add( new JButton( "South" ), BorderLayout.SOUTH );
      card3.add( label3, BorderLayout.CENTER );
      bSWest.addActionListener( this ) ;
      bSEast.addActionListener( this ) ; 
 
      pStack.add( card1, label1.getText() ); // add card to deck
      pStack.add( card2, BorderLayout.CENTER ) ;
      pStack.add( card3, label3.getText() ); // add card to deck

      // create and layout buttons
      buttonPanel = new JPanel();
      buttonPanel.setLayout( new GridLayout( 4, 1 ) );
      bArray = new JButton[ cardNames.length ];

      for ( int i = 0; i < bArray.length; i++ ) {
         bArray[ i ] = new JButton( cardNames[ i ] );
         bArray[ i ].addActionListener( this );
         buttonPanel.add( bArray[ i ] );
      }

      // add pStack and JPanel buttons to the client area
      c.add( buttonPanel, BorderLayout.WEST );
      c.add( pStack, BorderLayout.CENTER );

      setSize( 450, 350 );
      show();
   }


   /** ****************************************************************
    * The actionPerformed() method responds to events caused by the
    * user pressing one of the buttons.
    * 1- Pressing button first causes the first panel (card1) to be 
    *    displayed
    * 2- Pressing button next causes the next panel to be displayed
    * 3- Pressing button last causes the last panel to be displayed
    * 4- Pressing button previous causes the previous panel to be 
    *    displayed
    * 5- Pressing button bSWest results in array being sorted in 
    *    ascending order
    * 6- Pressing button bEWest results in array being sorted in 
    *    descending order
    *
    ******************************************************************/
   public void actionPerformed( ActionEvent e )
   {
      if ( e.getSource() == bArray[ 0 ] )
         cardLayManager.first( pStack );       // show first card
      else if ( e.getSource() == bArray[ 1 ] )
         cardLayManager.next( pStack );        // show next card
      else if ( e.getSource() == bArray[ 2 ] )
         cardLayManager.previous( pStack );    // show previous card
      else if ( e.getSource() == bArray[ 3 ] )
         cardLayManager.last( pStack );        // show last card
      else if ( e.getSource() == bSWest ) {    // sort ascending
         bSort() ;
         output = "" ; 
         output += "Subscript\tValue \n" ; 
         output += "\tAscending \n" ; 
         len =   n2.length ;
         for ( int i = 0; i < len; i++ ) 
            output += i + "\t" + n2[ i ] + "\n";
         JTextArea outputArea = new JTextArea( 11, 4 );
         outputArea.setText( output );            

         JOptionPane.showMessageDialog( null, 
             outputArea,
               "Initializing an Array with an Initializer List",
                  JOptionPane.INFORMATION_MESSAGE );
      }   
      else if ( e.getSource() == bSEast) {   // sort descending
         bDesSort() ;
         output = "" ; 
         output += "Subscript\tValue \n" ; 
         output += "\tDescending \n" ; 
         len =   n3.length ;
         for ( int i = 0; i < len; i++ ) 
            output += i + "\t" + n3[ i ] + "\n";

         JTextArea outputArea = new JTextArea( 11, 4 );
         outputArea.setText( output );         

         JOptionPane.showMessageDialog( null, 
             outputArea,
               "Initializing an Array with an Initializer List",
                  JOptionPane.INFORMATION_MESSAGE );
      }   
   }

    /** *************************************************
     *  The bSort() method does the following: 
     *  1- Calculates the length of the n array
     *  2- Copies the elements of array n into array n2
     *  3- Performs a bubble sort
     *  4- Calls the swap() method to exchane two values
     *   
     ****************************************************/
   public void bSort() {

      int len =   a.length ;

      for ( int ii = 0; ii < len ; ii++ )
         n2[ ii ] = a[ ii ] ;

      for ( int pass = 0; pass < len ; pass++ )   // no. of passes
         for ( int ii = 0; ii <= len - 1; ii++ )   // one pass   
            if ( n2[ ii ] > n2[ ii + 1 ] )        // one comparison
               swapAscDes( n2, ii, ii + 1 );            // one swap
   }

    /** *************************************************
     *  The bDesSort() method does the following: 
     *  1- Calculates the length of the n array
     *  2- Copies the elements of array n into array n3
     *  3- Performs a bubble sort
     *  4- Calls the swap() method to exchane two values
     *    
     ****************************************************/
   public void bDesSort() {

      int len =   a.length ;

      for ( int ii = 0; ii < len ; ii++ )
         n3[ ii ] = a[ ii ] ;

      for ( int pass = 0; pass < len ; pass++ )   // no. of passes
         for ( int ii = 0; ii < len - 1; ii++ )   //  pass 1 to pass len     
            if ( n3[ ii ] < n3[ ii + 1 ] )        // compare two value
               swapAscDes( n3, ii, ii + 1 );      // swap
   }

   /** *****************************************************
     *  The swapAscDes() method swaps two elements of an array
     *  
     *******************************************************/
   public void swapAscDes( int c[], int first, int second )    {

      int tempHold ;  // temporary holding area for swap

      tempHold = c[ first ] ;         
      c[ first ] = c[ second ] ;  
      c[ second ] = tempHold ;
   }



   /** ************************************************************
    * The main(0 method is the entry point called by Java when this 
    * program is loaded into memory
    *
    ***************************************************************/
   public static void main( String args[] )
   {
      SumArray sa = new SumArray();

      sa.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
} /****************** End of SumArray class ************************/
 
Figure 4: SumArray Example Code


Methods used in the SumArray example

In the following table, you will find a brief description of some of the methods used in the example.

Methods Descriptions
CardLayout Methods
CardLayout() Creates a new card layout with gaps of size zero.
Container Methods
Container() Constructs a new Container.
getContentPane() Returns the contentPane object for this JApplet/JFrame.
JButton Methods
JButton(String text) Creates a button with text.
addActionListener(ActionListener l) Adds an ActionListener to the button.
JLabel Methods
JLabel(String text) Creates a JLabel instance with the specified text.
getText() Returns the text string that the label displays.
JOptionPane Methods
showMessageDialog(null, "alert", "alert", JOptionPane.INFORMATION_MESSAGE) Show an error/message dialog that displays the message, 'alert':
JPanel Methods
JPanel() Create
add(Component comp , Object constraints) Adds the specified component to the end of this container. Also notifies the layout manager to add the component to this container's layout using the specified constraints object.
setBackground(Color bg) Sets the background color of this component.
setLayout(LayoutManager mgr) Sets the layout manager for this container.
JTextArea Methods
JTextArea(int rows, int columns) Constructs a new empty TextArea with the specified number of rows and columns.
setText(String t) Sets the text of this TextComponent to the specified text.
Figure 5: SumArray API Method Description


SumArray .bat file

The following example is the Bat file used to compile and run the SumArray program.

 
javac  SumArray.java


java   SumArray 


 
Figure 6: Bat file used to compile and run SumArray example.

To run this example

To run this example,

  1. Cut and paste the code in Figure 4 and place it in a file called SumArray.java.
  2. Cut and paste the code in Figure 5 and place it in a file called SumArray.bat.
  3. Double click on the SumArray.bat file and you will see the following.



    Figure 7: Image of SumArray example.



The Array class

    provides static methods to dynamically create, access and manipulate Java array objects. This is not a primitive array structure (e.g., int, float, long double, etc.)

The Bubble sort






HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works