SHS DataStruct Module ICT-12-Reviewer

You might also like

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

BAGUIO COLLEGE OF TECHNOLOGY

Baguio City, Philippines

SUBJECT TITLE : Data Structures and Algorithms


MODULE TITLE : Review Material
MODULE NO : 9
NOMINAL DURATION: 4 Hours
LEARNING OBJECTIVES:
After completing this module, the students should be able to:
1. know what specific topics to review in preparation for the 1st quarter examination;
2. have a deeper understanding of the important topics from the previous modules.

MODULE CONTENT:
Module 1-2: REFRESHER ON ARRAYS / ARRAY ALGORITHMS
Array Summary - main points
Purpose To save large numbers of data elements, either primitives or objects.
Universal Almost all programming languages have arrays.
Array Declaration
Same type All elements in an array must be the same type, either primitive or object.
Declaration Precede variable with element type and square brackets. Eg,
int[] scores;

Allocation Memory to store array elements must be allocated with new. Eg,
int[] scores; // Declares that scores is an array of integers.
scores = new int[12]; // Allocate memory to hold up to 12 score values.

Combined It's very common to combine the declaration with the allocation.
int[] scores = new int[12];//Declare and allocate memory in one statement.

Fixed size When memory is allocated for an array, it is a fixed size block. It does not expand.
Names The most common naming advice is to use plural names or collective nouns.
References Array variables are references to array objects. Two variables can reference the same array.
Array initial values
zero/null If no initial values are specified for array elements (see below), array elements are initialized to zero for
numbers, null for object references. This is the same as for all object fields.
Initialization A curly brace surrounded list of values can be specified on the declaration. This allocates exactly enough
space to hold the array. The following are equivalent.
String[] names = {"Juan", "Mario", "Julia"}; String[] names = new
String[3];
names[0] = "Juan";
names[1] = "Mario";
names[2] = "Julia";

Subscripts - Accessing elements of the array


Integers Selecting a particular position in an array is done by specifying an integer value.
Square Subscripts are written after an array variable, enclosed in square brackets.
brackets scores[5] = 86; // Assigns the value 86 as the 5th value.
scores[ss]++; // Increments the score of element whose number is in ss.
Start at 0 The first subscript value is zero, not one.
Bounds ArrayIndexOutOfBoundsException is thrown if subscripts are out of the legal range.
check

Iterating over an array


Length/size The size of an array can be found by referencing the length field, eg, scores.length .

BCT LEARNING MODULES S.Y. 2020-2021 1


BAGUIO COLLEGE OF TECHNOLOGY
Baguio City, Philippines

For loops for loops are the most common way to iterate over array elements. The normal for loop is good for
going forwards, backwards, sub-ranges, comparing two elements, or on every nth element. If you are
just going forward over the entire array, the enhanced for loop is more readable.
//... Using standard for loop.
int[] scores = new int[12];
. . . Set values in the scores array.
int total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}

Module 3: Two-Dimensional Arrays


Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ...
In practice most arrays are one-dimensional, and two-dimensional (rows and columns) are also quite common.
Two-dimensional arrays are used whenever the model data is best represented with rows and columns, or has two
varying aspects (e.g., gender and age, weight and height, ...). It's also the idea, although not the implementation, of
graphics that specifies a two (or three) dimensional position with an x and y (and z) coordinate.
Terminology. Other terms you will see for a two-dimensional array are matrix or table.
Visualizing two-dimensional arrays
2-dimensional arrays are usually represented with a row-column "spreadsheet" style. Assume we have an array, a,
with two rows and four columns.
int[][] a = new int[2][4]; // Two rows and four columns.

Two-dimensional arrays are usually visualized as a matrix, with rows and columns.
a[0][0] a[0][1] a[0][2] a[0][3] This diagram shows the array a with its corresponding subscripts.
a[1][0] a[1][1] a[1][2] a[1][3]

Style: Use named constants for array sizes


It's useful to define constants for the number of rows and columns. The reason named constants can better code is
that these numbers may represent part of the problem domain and they will be used in other parts of the code. If a
change is every necessary (e.g., the number of teams in the Big Ten), changing one named constant will change all
parts of the program. Each numeric "constant" should only appear once (the "DRY" principle).
static final int ROWS = 2;
static final int COLS = 3;
. . .
int[][] board = new int[ROWS][COLS];

Many row and column indexes have a meaning, and aren't just simply arbitrary numbers. The following example
might be used to represent the number of accidents on the day of the month and the hour of the day. See
programming problems below for some examples using this array.
static final int DAYS = 31;
static final int HOURS = 24;
. . .
int[][] accidents = new int[DAYS][HOURS];

Initial values
You can assign initial values to an array in a manner very similar to one-dimensional arrays, but with an extra level
of braces. The dimension sizes are computed by the compiler from the number of values. This would allocate a 3x3
board
int[][] board = new int[][] {{1,0,0},{0,1,0},{1,2,1}};

BCT LEARNING MODULES S.Y. 2020-2021 2


BAGUIO COLLEGE OF TECHNOLOGY
Baguio City, Philippines

Use nested for loops to process 2-dimensional arrays


Index names. Two-dimensional arrays are almost always processed with nested for loops. The two index variables
are often called i and j (for the row and column), but it is better to use row and col or r and c. However, if the row
and column have meanings, like month and year, use those names rather than a meaning neutral name.
Iterating down rows, then across columns is often better. The most common practice is for the outer loop be for
the row and the inner loop for the column. If your program requires the outer iteration by columns, that's fine, but
the default row-first iteration gives the best performance because "locality of reference" improves the performance
of cache and virtual memory.
Module 4: ArrayList
A collection is a group of related objects, or elements, that are stored together as a single unit. An array
is an example of a collection. Java also contains a collections framework, which provides classes for
implementing collections. One such class is the ArrayList class, which includes methods for adding and
deleting elements and finding an element.
Class ArrayList (java.util.ArrayList)
Methods:
add(int index, Object element) inserts element at index position of the array. Existing elements are
shifted to the next position up in the array.
add(Object element) adds element to the end of the array.
get(int index) returns the element at index position in the array.
indexOf(Object obj) returns the index of the first element matching obj using the
equals() method of the object’s class to determine equality between
the element and the object.
remove(int index) removes the element at index position in the array.
set(int index, Object element) replaces the element at index position with element.
size() returns the number of elements in the array.

The ArrayList class implements a dynamic array. A dynamic array varies in size during run time and is used
in applications where the size of an array may need to grow or shrink. An ArrayList object shifts elements
up one position when a new element is added at a specific index. Elements added to the end of the
ArrayList do not move existing elements. Removing an element from an ArrayList also shifts elements as
necessary to close the gap left by the removed element.
When using an ArrayList object, it is important to understand that only objects, not primitive types, can
be stored. Because the indexOf() method compares its object parameter to each element of the array,
it is important that the object’s class has an appropriately overridden equals() method.
Module 5: Bubble Sort Algorithm
Bubble sort is a simple algorithm which compares neighboring elements and swaps them if they are not
in the order.
public int[] bubbleSort(int[] data){
int lenD = data.length;
int tmp = 0;
for(int i = 0;i<lenD;i++){
for(int j = (lenD-1);j>=(i+1);j--){
if(data[j]<data[j-1]){
tmp = data[j];
data[j]=data[j-1];
data[j-1]=tmp;
}
}
}
return data;
}

BCT LEARNING MODULES S.Y. 2020-2021 3


BAGUIO COLLEGE OF TECHNOLOGY
Baguio City, Philippines

Module 6: Selection Sort Algorithm


Selection sort is the sorting algorithm where the element on active position (say ith position) is compared
with other positions (say i+1th to nth position) and swaps if it’s larger than the compared element.
public int[] selectionSort(int[] data){
int lenD = data.length;
int j = 0;
int tmp = 0;
for(int i=0; i<lenD; i++){
j = i;
for(int k = i; k<lenD; k++){
if(data[j]>data[k]){
j = k;
}
}
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
return data;
}

Module 7: Recursion
In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion.
A physical world example would be to place two parallel mirrors facing each other. Any object in between
them would be reflected recursively.
How Recursion works?

In the above example, we have called the recurse() method from inside the main method (normal
method call). And, inside the recurse() method, we are again calling the same recurse method. This
is a recursive call.
In order to stop the recursive call, we need to provide some conditions inside the method. Otherwise, the
method will be called infinitely.
Hence, we use the if...else statement (or similar approach) to terminate the recursive call inside the
method.
Module 8: Stack Data Structure
The stack is a linear data structure that is used to store the collection of objects. It is based on the Last
In-First-Out (LIFO) algorithm. Java collection framework provides many interfaces and classes to store
the collection of objects. One of them is the Stack class that provides different operations such as push,
pop, peek, etc.
There are many real-life examples of a stack. Consider the simple example
of plates stacked over one another in a canteen. The plate which is at the
top is the first one to be removed, i.e. the plate which has been placed at
the bottommost position remains in the stack for the longest period of
time. So, it can be simply seen to follow LIFO order.

BCT LEARNING MODULES S.Y. 2020-2021 4


BAGUIO COLLEGE OF TECHNOLOGY
Baguio City, Philippines

Following are some of the important applications of a Stack data structure:


1. Stacks can be used for undo-redo features of software applications.
2. Stacks can be used for expression evaluation.
3. Stacks can be used to check parenthesis matching in an expression.’ 4. Stacks can be used for
Conversion from one form of expression to another.

5. Stacks can be used for Memory Management.


6. Stack data structures are used in backtracking problems.
The stack data structure has the two most important operations
that are push and pop. The push operation inserts an element
into the stack and pop operation removes an element from the
top of the stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack. Let's
remove (pop) 18, 45, and 11 from the stack.

REFERENCES: References are the same as with the previous modules.

Prepared by: GERARDO C. DACANAY (Teacher)

BCT LEARNING MODULES S.Y. 2020-2021 5

You might also like