Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

MODULE 4

MODULE TITLE: Dynamic Arrays

OVERVIEW

This module discusses the concept of dynamic arrays. Various techniques and algorithms
to manipulate dynamic arrays are also covered.

MODULE OBJECTIVES:

At the end of this module, the students should be able to:

 Discuss the difference between static and dynamic arrays

 Create programs using dynamic arrays

 Implement various techniques in manipulating dynamic arrays

42 | P a g e
PRE-TEST

Name: Score:

Section: Instructor: Date:

Directions: Encircle ‘T’ if the statement is correct. Otherwise, encircle ‘F’. (10 points)

T | F 1. A static array is a variable-size list data structure that allows elements to be added
or removed.

T | F 2. Elements are added at the end of the dynamic array.

T | F 3. To delete an element from a dynamic array, the last element is removed.

T | F 4. The first element of an array can be found at index 0.

T | F 5. Resizing a dynamic array involves allocating a new array and copying each
element from the original array.

T | F 6. If the length of an array is n, the first element of the array will be arrayName[0]
and the last element will be arrayName[n-1].

T | F 7. An array can hold multiple values with different data types.

T | F 8. Resizing a dynamic array requires O(n2) time.

T | F 9. If we did not store any value to an array, the array will store some default value (0
for int type and true for boolean type) by itself.

T | F 10. After deleting an element from the dynamic array, all elements at the left side of
the selected index are shifted to the right.

43 | P a g e
CONTENTS

An array is a container object that holds a fixed number of values of a single type. The length of
an array is established when the array is created. The length is fixed after creation.

A dynamic array is a variable-size list data structure that allows elements to be added or
removed. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that
needs to be specified at allocation.

A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger
than the number of elements immediately required. The elements of the dynamic array are stored
at the start of the underlying array, and remaining positions towards the end of the array are
reserved or unused. Elements can be added at the end of the dynamic array by using reserved
space until the space is completely consumed. The underlying fixed-size array needs to be
increased in size when further elements have to be added after all the space is consumed.
Typically resizing is expensive as it involves allocating a new array and copying each element
from the original array (costs O(n) time).

A fixed-size array will suffice in scenarios where the maximum logical size is fixed. A dynamic
array will be needed when the maximum logical size is unknown initially, or likely to change.

Add an Element to a Dynamic Array

As discussed in the previous section, elements are added at the end of an array. A new array
(typically double the original array size) is created and data is copied from original array to the
new one after the allocated space is consumed.

Delete an Element from a Dynamic Array

To delete an element from a dynamic array, the element at the index specified by the user is
removed. After that, all elements at the right side of the index are shifted to the left.

44 | P a g e
Resize an Array

An array’s size can be increased or decreased. Resizing is usually an expensive operation, as it


would mean creating a new array and copying all the elements (costs O(n) time).

To illustrate the concepts discussed earlier, let’s consider the sample program below:

DynamicArray.java

public class DynamicArray {

private int array[];


// holds the current size of array
private int size;
// holds the total capacity of array
private int capacity;

// constructor to initialize the array


public DynamicArray(int initCapacity){
array = new int[initCapacity];
size = 0;
capacity = initCapacity;
}

// get method for the size


public int getSize() {
return size;
}

// get method for the capacity


public int getCapacity(){
return capacity;
}

// get method for the element at the index specified by the parameter
public int getElement(int index){
return array[index];
}

// method for adding an element to the array


public void addElement(int element){
// double the capacity if all the allocated space is utilized
45 | P a g e
if (size == capacity){
increaseCapacity();
}
array[size] = element;
size++;
}

// method to increase the capacity of the array


public void increaseCapacity() {
// creates a second array with size twice the original
int temp[] = new int[capacity*2];
// the values of the original array are transferred to the second
For (int i=0; i<capacity; i++) {
temp[i] = array[i];
}
// overwrites the original array with the second
array = temp;
// updates the capacity
capacity = capacity * 2;
}

// method to remove an element at the index specified by the parameter


public void removeElement(int index){

if(index>=size || index<0)
System.out.println("No element at this index");
else {
for(int i=index;i<size-1;i++)
array[i] = array[i+1];
array[size-1]=0;
size--;
}
}
}

Test.java

import java.io.*;

public class Test {

public static void main(String args[]) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

// holds the initial capacity of the array


int initCapacity;
// holds the index to be deleted
int delIndex;

// sets the initial size of the array


System.out.print("\nEnter size of the array: ");
initCapacity = Integer.parseInt(reader.readLine());

46 | P a g e
// creates the dynamic array
DynamicArray dynamicArray = new DynamicArray(initCapacity);

System.out.print("\nSuccessfully created the dynamic array!");


System.out.print("\nCurrent Size: " + dynamicArray.getSize());
System.out.println("\nCurrent Capacity: " + dynamicArray.getCapacity());

// assign values to the array


System.out.print("\nAdding elements to the array...");
for(int i=0; i<initCapacity; i++) {
System.out.print("\nEnter a number: ");
dynamicArray.addElement(Integer.parseInt(reader.readLine()));
}

// displays the array information


System.out.print("\nCurrent Size: " + dynamicArray.getSize());
System.out.print("\nCurrent Capacity: " + dynamicArray.getCapacity());
System.out.print("\nThe values of the array are: ");
for(int i=0; i<dynamicArray.getSize(); i++)
System.out.print(" " + dynamicArray.getElement(i));

// removes an element from the array


System.out.print("\n\nEnter index to be removed: ");
delIndex = Integer.parseInt(reader.readLine());
dynamicArray.removeElement(delIndex);

// displays the array information


System.out.print("\nCurrent Size: " + dynamicArray.getSize());
System.out.print("\nCurrent Capacity: " + dynamicArray.getCapacity());
System.out.print("\nThe values of the array are: ");
for(int i=0; i<dynamicArray.getSize(); i++)
System.out.print(" " + dynamicArray.getElement(i));
}
}

47 | P a g e
Below is the output of the program:

48 | P a g e
POST-TEST

Name: Score:

Section: Instructor: Date:

I. True or False. Encircle ‘T’ if the statement is correct. Otherwise, encircle ‘F’. (10 points)

T | F 1. Elements are added at the end of the dynamic array.

T | F 2. A dynamic array is a variable-size list data structure that allows elements to be


added or removed.

T | F 3. To delete an element from a dynamic array, the last element is removed.

T | F 4. Resizing a dynamic array involves allocating a new array and copying each
element from the original array.

T | F 5. Resizing a dynamic array requires O(n2) time.

T | F 6. After deleting an element from the dynamic array, all elements at the right side of
the selected index are shifted to the left.

T | F 7. The first element of an array can be found at index 0.

T | F 8. The time complexity of traversing an array is O(1) because each element is


accessed only once.

T | F 9. If we did not store any value to an array, the array will store some default value (0
for int type and false for boolean type) by itself.

T | F 10. You can create an array by using the new operator.

II. Output Tracing. Trace and write the output of the following Java statements. If the
statements will result to a compile-time or runtime error, do not write anything except ERROR
as your answer. Write your answers in the space provided. (2 points each)

Java Statements Output

1. int[] numbers = {-5,3,4,-2,1};


for(int i=numbers.length-1; i>0; i--) {
numbers[i] += numbers[i-1];
System.out.print(numbers[i]+" ");
}

49 | P a g e
2. int[] numbers = {7,3,8,-11,3};
for(int i=1; i<numbers.length-1; i++) {
numbers[i-1] = ++numbers[i] + numbers[i+1];
System.out.print(numbers[i-1]+" ");
}

3. int[] numbers = {-2,3,-5,-7,4};


for(int i=0; i<numbers.length-1; i++) {
if(!(numbers[i]<=numbers[i+1]))
System.out.print(numbers[i] + " ");
else
System.out.print(numbers[i+1] + " ");
}

4. int[] numbers = {4,2,1,5,3,6,8};


for(int i=0; i<numbers.length-1; i++){
if(numbers[i]%2==0)
numbers[i] = numbers[i] + numbers[i+1];
else
numbers[i] = numbers[i] - numbers[i+1];
System.out.print(numbers[i] + " ");
}

5. int[] numbers = {-5,2,-1,5,-3,6,-8};


for(int i=0; i<numbers.length-1; i++){
if(numbers[i]<0)
numbers[i] = numbers[i] + numbers[i+1];
else
numbers[i] = numbers[i] - numbers[i+1];
System.out.print(numbers[i] + " ");
}

50 | P a g e
MODULE TEST

Name: Score:

Section: Instructor: Date:

I. True or False. Encircle ‘T’ if the statement is correct. Otherwise, encircle ‘F’. (10 points)

T | F 1. Resizing a dynamic array requires O(1) time.

T | F 2. Elements are added at the end of the dynamic array.

T | F 3. A static array is a variable-size list data structure that allows elements to be added
or removed.

T | F 4. To delete an element from a dynamic array, the last element is removed.

T | F 5. Resizing a dynamic array involves allocating a new array and copying each
element from the original array.

T | F 6. After deleting an element from the dynamic array, all elements at the right side of
the selected index are shifted to the left.

T | F 7. As with variables of other types, the declaration of an array does not actually create
an array; it simply tells the compiler that this variable will hold an array of the
specified type.

T | F 8. int a[]={33,3,4,5}; is a valid statement to declare, create and initialize an array.

T | F 9. You can access the length of an array via its size property.

T | F 10. String[] strings = {"one", "two", "three"}; is a valid statement to declare, create and
initialize an array.
II. Programming

Problem

Write a program to insert an element (specific position) into an array. (32 points)

Sample Output

Enter size of the array: 3


Enter a number: 1
Enter a number: 2
51 | P a g e
Enter a number: 3
The elements are: 1 2 3

Enter index to insert: 1


Enter value to insert: 10
The elements are: 1 10 2 3

Grading Rubric

52 | P a g e
REFERENCES

Textbook:

[1] Malik D. S. 2019. C++ Programming including Data Structures. Cengage Learning.

Online Resources:

[2] JavaCodeGeeks. 2019. Dynamic Array Java Example. Retrieved May 10, 2020 from
https://examples.javacodegeeks.com/dynamic-array-java-example/

[3] TutorialsPoint. 2020. Data Structures - Algorithms Basics. Retrieved May 10, 2020
https://www.tutorialspoint.com/data_structures_algorithms/algorithms_basics.htm

[4] Friesen J. 2017. Data structures and algorithms in Java, Part 1: Overview. Retrieved May
10, 2020 from https://www.javaworld.com/article/3215112/java-101-datastructures-and-
algorithms-in-java-part-1.html

53 | P a g e

You might also like