Tutorial: Using our fill(), sort() and binarySearch() methods


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/Arrays_Demo.html">An Introduction to the fill() and sort() methods </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. Arrays are implicit extensions of the Object class, so you can assign an array to a variable whose type is declared as Object. Arrays are:

  • Data structures consisting of related data items of the same type
  • Static - remain the size once they are created
  • An array is 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 posessions; 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

ArraysDemo template

In the following table, we will show an ArraysDemo code snippet.

 
/** **************************************************************
 * ArraysDemo.java demonstrates the use of the Array class methods
 * 1- sort()
 * 2- fill()
 * 3- binarySearch(() 
 * 
 ****************************************************************/

import java.util.Arrays;
import javax.swing.* ;

public class ArraysDemo {

   /** **************************************************************
    * The ArraysDemo() constructor's logic is as follows:
    * 1- Call displayArray() method to list the elements in the array
    *    - it is unsorted
    * 2- Sort array - 
    * 3- Fill the array using a fill number.
    * 4- Display the array after using a fill number. 
    * 5- Sort the array after using a fill number.  
    * 6- Display the array after using a fill number. 
    * 7- Use a binary search on the array for 305. 
    * 8- Use JOptionPane to display the results of the binary search.
    * 
    ****************************************************************/
   public ArraysDemo() {

   }

   /** **************************************************************
    * The displayArray() method displays a message and lists the 
    * elements of the passed array.
    * 1- int array[] is a reference to the passed array.
    * 2- String str is the passed message.
    * 3- Create a new string starting with str.
    * 4- Add to this new string the elements in the array.
    * 5- Use JOptionPane to display string that list the array 
    *    elements
    * 
    ****************************************************************/
   void displayArray(int array[] , String str ) {

   }

  /** **************************************************************
   * The main() method is the entry point that is called by Java when 
   * this program is loaded into memory.
   * 
   ****************************************************************/
   public static void main(String args[]) {
      ArraysDemo ad = new ArraysDemo() ;
   }
}

/****************** End of ArraysDemo class ************************/ 

 
 
Figure 3: ArraysDemo template

ArraysDemo code example



  
/** **************************************************************
 * The ArraysDemo.java program demonstrates the use our fill(), 
 * sort() and binarySearch() methods.
 *  
 * 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 java.util.Arrays;
import javax.swing.* ;

public class ArraysDemo {

   private int array[] = {5, 15, 105, 305, 1455, 87, 103, 15, 25, 45, 65} ;
   private String output = "" , str = "" ;
   private int len = array.length ;

   /** **************************************************************
    * The ArraysDemo() constructor's logic is as follows:
    * 1- Call displayArray() method to list the elements in the array
    *    - it is unsorted
    * 2- Sort array - 
    * 3- Fill the array using a fill number.
    * 4- Display the array after using a fill number. 
    * 5- Sort the array after using a fill number.  
    * 6- Display the array after using a fill number. 
    * 7- Use a binary search on the array for 305. 
    * 8- Use JOptionPane to display the results of the binary search.
    * 
    ****************************************************************/
   public ArraysDemo() {

      displayArray( array, "Array is unsorted" ) ;
      bSort( array ) ;
      displayArray( array, "Array is now sorted" ) ;
      
      myFill( array, 2, 6, -1 );     
      displayArray( array, "After fill() using -1: " ); 
       
      bSort( array ) ;
      displayArray(array, "After fill() sort again: ");     

      output = "" ;
      int index = binarySearch(array, 305);
      if ( index >= 0 ) {
         output += "The value 305 is at location " + index + "\n" ;
      }
      else {
         output += "The value 305 was not found."  + "\n" ;
      }

      for (int i = 0 ; i < len ; i++) {
         output += array[ i ] + "\n" ;
      }   

      JOptionPane.showMessageDialog( null, 
             output,
             str,
             JOptionPane.INFORMATION_MESSAGE );

   }

   /** ******************************************************
    * binarySearch() method performs a binary search of an 
    * array. the logic is:
    * 1- Declare variables
    * 2- Loop until low-end subscript is greater than high-end 
    *    index
    * 3- Calculate the middle element of the array
    * 4- Determine if key matches middle element, return middle 
    *    location
    * 5- If key less than middle element, set middle element 
    *    to high element
    * 6- If key is greater than middle element, set low-end  
    *    index = middle+1
    * 
    *********************************************************/
   public int binarySearch( int array[], int key )    { 
      int ii = 0 ;                     // first index  
      int loopEnd = array.length - 1 ; // last element's index
      int middle = -1 ;                // middle index
      int retValue  = 0 ;

      while ( ii <= loopEnd ) {
         middle = ( ii + loopEnd ) / 2;

         if ( key == array[ middle ] )  {  // match
            retValue = middle;   
            break;             
         }
         else if ( key < array[ middle ] ) // search first half of array
            loopEnd = middle - 1;           
         else
            ii = middle + 1;               // search second half of array
      }      

      return retValue  ; 
   }

   /** **************************************************************
    * The displayArray() method displays a message and lists the 
    * elements of the passed array.
    * 1- int array[] is a reference to the passed array.
    * 2- String str is the passed message.
    * 3- Create a new string starting with str.
    * 4- Add to this new string the elements in the array.
    * 5- Use JOptionPane to display string that list the array 
    *    elements
    * 
    ****************************************************************/
   void displayArray(int array[] , String str ) {
      int len ;
      output = str + "\n" ;

      len = array.length ;
      for (int i = 0 ; i < len ; i++) {
         output += array[ i ] + "\n" ;
      }   

      output += "\n" ;

      JOptionPane.showMessageDialog( null, 
             output,
             str,
             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 a[] ) {

      int len =   a.length ;
      int passes =  0 ;

      for ( int pass = 0; pass < len ; pass++ )    // no. of passes
         for ( int ii = 0 ; ii < len - 1; ii++ ) {  // one pass   
            if ( a[ ii ] > a[ ii + 1 ] )         // one comparison
               swapAscDes( a, ii, ii + 1 );            // one 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 myFill() method fills the passed array with a   
     *  fill number starting with the element at the   
     *  startIndex up to the element endIndex.
     *  
     *******************************************************/      
   public void myFill( int a[] , int startIndex, int endIndex, 
                            int fillNumber ) { 

      for ( int ii = startIndex ; ii < endIndex ; ii++ ) {
         a[ ii ] = fillNumber ;
      }
   } 


  /** **************************************************************
   * The main() method is the entry point that is called by Java when 
   * this program is loaded into memory.
   * 
   ****************************************************************/
   public static void main(String args[]) {
      ArraysDemo ad = new ArraysDemo() ;
   }
}/*********************  End of ArraysDemo class  ******************/
 
Figure 4: ArraysDemo Example Code


ArraysDemo .bat file

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

 
javac        ArraysDemo.java


appletviewer ArraysDemo.html


 
Figure 5: Bat file used to compile and run ArraysDemo 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 ArraysDemo.java.
  2. Cut and paste the code in Figure 5 and place it in a file called ArraysDemo.bat.
  3. Double click on the ArraysDemo.bat file and you will see the following.



    Figure 6: Image of ArraysDemo example.








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

© 2002 - 2016 All Rights Reserved Total Application Works