Single - Dimensional Arrays

Chapter 7

Code Repo

Introducing Arrays

  • Array is a data structure that represents a collection of the same types of data.

Advantage

  • Allows you to store large number of values of same type
  • Better than creating multiple variable of same type

Disadvantage

  • We must know the size of a array in advance
  • Cannot grow dynamically after created.
  • Memory space is wasted if we allocate more memory than required

Array Example

Code
  • Array print days
                        
                        

Declaring Array Variables


                        datatype[] arrayRefVar;
                        Example: 
                        double[] myList;
                    
                    datatype arrayRefVar[]; // This style is allowed, but not preferred
                        Example: 
                        double myList[];
                    
                    

Creating Arrays

  • arrayRefVar = new datatype[arraySize];
  • Example: myList = new double[10];
  • myList[0] references the first element in the array.
  • myList[9] references the last element in the array.


                            datatype[] arrayRefVar = new datatype[arraySize];
                            double[] myList = new double[10];

                            datatype arrayRefVar[] = new datatype[arraySize];
                            double myList[] = new double[10];

                        
                        

The Length of an Array

Once an array is created, its size is fixed. It cannot be changed. You can find its size using


                            public class TestVoidMethod {
                                double[] arrayRefVar = new double[10];
                                arrayRefVar.length
                                For example,
                                arrayRefVar.length returns 10
                                
                              }
                        

Default Values

When an array is created, its elements are assigned the default value of


                0 for the numeric primitive data types, 
                '\u0000' for char types, and 
                false for boolean types. 

              

Indexed Variables

  • The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. In the example, myList holds ten double values and the indices are from 0 to 9.
  • Each element in the array is represented using the following syntax(arrayRefVar[index];), known as an indexed variable:

Using Indexed Variables

  • After an array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the value in myList[0] and myList[1] to myList[2].


                            
                            double[] myList = {1, 2, 3, 4};
                            myList[2] = myList[0] + myList[1];
                            System.out.println(myList[2]);

                      
                        

Array Initializers

  • Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5};
  • This shorthand syntax must be in one statement.


                            
                            double[] myList = {1.9, 2.9, 3.4, 3.5};

                            String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars[0]); 
                            String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; 
                            cars[0] = "Opel"; 
                            System.out.println(cars[0]); // Now outputs Opel instead of Volvo 


                      
                        

Declaring, creating, initializing Using the Shorthand Notation

  • Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5};
  • This shorthand notation is equivalent to the following statements:


                            
                            double[] myList = {1.9, 2.9, 3.4, 3.5};

                            double[] myList = new double[4];
                            myList[0] = 1.9;
                            myList[1] = 2.9;
                            myList[2] = 3.4;
                            myList[3] = 3.5; 


                      
                        

CAUTION

  • Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong:

                        //This is incorrect
                        double[] myList;
                        myList = {1.9, 2.9, 3.4, 3.5}; 

                        //This is correct
                        double[] myList= {1.9, 2.9, 3.4, 3.5}; 

                        

Initializing arrays with input values


                        java.util.Scanner input = new java.util.Scanner(System.in);
                        System.out.print("Enter " + myList.length + " values: ");
                        for (int i = 0; i < myList.length; i++) {
                          myList[i] = input.nextDouble();
                        }

                        

Initializing arrays with random values


                        for (int i = 0; i < myList.length; i++) {
                            myList[i] = Math.random() * 100;
                          }
                          

                        

Printing arrays


                         double[] myList = {1, 2, 3, 4};
                         for (int i = 0; i < myList.length; i++) {
                            System.out.print(myList[i] + " ");
                          }
                          

                          // Array with random number
                            int[] myList1 = new int[2];
                            for (int i = 0; i < myList1.length; i++) {
                                myList1[i] = (int) (Math.random() * 100);
                                System.out.println( myList1[i] );
                            }
                        
                        

Summing all elements


                        //Sum array values
                        double[] myList = {1, 2, 3, 4};
                        int total=0;
                         for (int j = 0; j < myList.length; j++) {
                            total+=myList[j];
                         }
                         System.out.println( total);
                          

                        

Finding the largest element


                        double[] myList = {1, 2, 3, 4};
                        double max = myList[0];
                        for (int i = 1; i < myList.length; i++) {
                          if (myList[i] > max) max = myList[i];
                        }
                        

                        

Copying Arrays

Often, in a program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1;

Copying Arrays

     
                       # Using a loop:
                        int[] sourceArray = {2, 3, 1, 5, 10};
                        int[] targetArray = new int[sourceArray.length];
                        
                        for (int i = 0; i < sourceArrays.length; i++)
                           targetArray[i] = sourceArray[i];
                        
    
    
                            

The arraycopy Utility

  • arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);
  • Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
  • Classwork use arraycopy method
  •  
                           
                            
                            public static void main(String[] student) {
    
                                int arr1[] = { 0, 1, 2, 3, 4, 5 };
                                int arr2[] = { 5, 10, 20, 30, 40, 50 };
                                System.arraycopy(arr1, 0, arr2, 0, 2);
                        
                                System.out.print("arr2 = ");
                                System.out.print(arr2[0] + " ");
                                System.out.print(arr2[1] + " ");
                                System.out.print(arr2[2] + " ");
                                System.out.print(arr2[3] + " ");
                                System.out.print(arr2[4] + " ");
                        
                        
                            }
                        /*
                        Parameters
                        src − This is the source array.
                        srcPos − This is the starting position in the source array.
                        dest − This is the destination array.
                        destPos − This is the starting position in the destination data.
                        length − This is the number of array elements to be copied.
                        Return Value
                        This method does not return any value.
                        */
        
                                

Passing Arrays to Methods

Anonymous Array

  • The statement printArray(new int[]{3, 1, 2, 6, 4, 2});
  • creates an array using the following syntax: new dataType[]{literal0, literal1, ..., literal};
  • There is no explicit reference variable for the array. Such array is called an anonymous array.
 
                        printArray(new int[]{3, 1, 2, 6, 4, 2}); 
     
 
                             

Searching Arrays

  • Searching is the process of looking for a specific element in an array
  • for example, discovering whether a certain score is included in a list of scores
  • Searching is a common task in computer programming.
  • There are many algorithms and data structures devoted to searching
  • In this section, two commonly used approaches are discussed, linear search and binary search.
 
                        
                       //Linear Search code
                        public static int linearSearch(int[] list, int key) {
                                 for (int i = 0; i < list.length; i++) {
                                    if (key == list[i])
                                      return i;
                                  }
                                  return -1;
                                }
   
                     

LINEAR SEARCH

  • A linear search scans one item at a time, without jumping to any item .
  • The worst case complexity is O(n), sometimes known an O(n) search
  • Time taken to search elements keep increasing as the number of elements are increased.

Linear Search

How Linear Search Works?

Linear Search Code

Github code sample Linear Search

                            
                            

Binary Search

  • Search a sorted array by repeatedly dividing the search interval in half. 
  • Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
  • Otherwise narrow it to the upper half. Repeatedly check until the value is found, or the interval is empty.

Binary Search

How Binary Search Works?

Binary Search Code

Github code sample Binary Search

                            
                            

THE END

Questions/Suggestions

- Lab 4
- Group Project Task #3