0% found this document useful (0 votes)
207 views25 pages

Data Structure & Algorithm

This document provides an overview of data structures and algorithms. It discusses programming languages and how they are used to solve problems through structured, event-driven, procedural, and object-oriented programming. The document then defines data structures and algorithms, and how they are used to store and organize data in a program. It provides examples of common data structures like lists, arrays, stacks and queues. The document also covers algorithm analysis and big O notation for analyzing time and space complexity. It demonstrates how algorithms are used to solve problems and examples of writing algorithms in Java using methods, loops, and conditionals.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
207 views25 pages

Data Structure & Algorithm

This document provides an overview of data structures and algorithms. It discusses programming languages and how they are used to solve problems through structured, event-driven, procedural, and object-oriented programming. The document then defines data structures and algorithms, and how they are used to store and organize data in a program. It provides examples of common data structures like lists, arrays, stacks and queues. The document also covers algorithm analysis and big O notation for analyzing time and space complexity. It demonstrates how algorithms are used to solve problems and examples of writing algorithms in Java using methods, loops, and conditionals.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

ITE 031

MODULE 1: DATA STRUCTURE AND


ALGORITHM

Book Reference:

Data Structure and Algorithms Made Easy:Data Structures and Algorithmic Puzzles

By: Narasimha KarumanchI

Java how to program(4th edition)

Deitel & Deitel

PROGRAMMING LANGUAGE
- vocabulary and set of grammatical rules for instructing a computer or computing device to
perform specific tasks.
- a special way of talking to computers. They're made up of a bunch of instructions that tell
the computer what to do.
- different styles of programming, like structured, event-driven, procedural, and
object-oriented programming, to solve complex problems. It all depends on what you're
trying to do and how you want to organize your code.

DATA STRUCTURE AND ALGORITHM


-are all about how you store and organize data in your program. This is important because it can
affect how quickly you can access and use the data you need.

-can build your own compilers, interpreters and many other things to fathom your application
program. This is part of data science that calculates how your data is responding to the users’
request, calculating the size of the list or arrays running as flat data for your database and
related purposes.

● ALGORITHM is not a big deal, but a mention of steps to solve a problem. It is


just that algorithms are a roadmap solution to a problem.
● DATA STRUCTURE is a specialized format for organizing, processing, retrieving and
storing data. And applicable to all different types of programming languages.
● EXAMPLE: FINDING THE PRODUCT OF NUMBER USING THE OPERANDS &
OPERATORS.

PSEUDOCODE:

create a function -> add numbers


add(num1 and num2)
return num1 plus add2

call add function and inject two numbers


display the sum
Translate that algorithm into actual codes using Java.

static int add(int num1, int num2){


return (num1+num2);
}

int sum = add(10,2);


System.out.print(“sum is” + “ “ + sum);

JAVA is known for oop and its rich package libraries especially in data structure,
no need to invent the wheel but to apply the existing built in class of array,
arraylist, stack , queue, node and tree.

MODULE 2: ALGORITHM ANALYSIS


Algorithms -a tool to resolve the problem of data.
Data Structure -art of organizing the data.

The “hello world” is a stringtype , it is organized as a string to match the requirements


of the statement in the program.

#include <iostream>

using namespace std;

int main() {

string msg= "hello world";


std::cout << msg << endl;

return 0;

1. Lists. A list contains elements of one particular data type


2. Array. An array is a data structure where the elements are identified by one
or more indices.
3. Stacks. A stack is a data structure where elements are only inserted or deleted
at the top.
4. Queue- a linear data structure that is open at both ends and the operations are
performed in First In First Out (FIFO) order.
Casting of Data - Retrieve the information with the same values. And the values
should be converted to double. Meaning from int to double.

WIDEN CASTING is done automatically when passing a smaller size type to a larger size type:

public class Main {


public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}

NARROWING CASTING must be done manually by placing the type in parentheses in front of the value:

public class Main {


public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}

Example:
public class Module2{
public static void main(String [] args){
int i=100; // declare a variable; assign 200 to i
String s=String.valueOf(i);
//Convert i to string to concatenate the String
System.out.println(i+100);//200 because + is binary plus operator
System.out.println(s+100);//100100 because + is string concatenation operator
}
}

1. Java implicit conversion from int to double without typecasting.


2. Java – Convert int to double using double wrapper class.

How to convert int to double in Java.

public class Module2_1{


public static void main(String args[])}
int num1 = 201;
double d_num1 = num1; // int to double conversion without typecasting
System.out.println(“double d_num = num->int to double conversion without typecasting”);
System.out.println(d_num1);
}1
}
Programming language for Data Structure.

● High-level languages like Python and Ruby are often suggested because they are high level and
the syntax is quite readable. However, these languages all have abstractions for the common
data structures. But the best way to learn data structure is to use C++ or Java, they are
syntactically the same, except for the fact that C++ is for low programming, it is compiled and
communicates well to computer registers.

● And java? It is a high level language.


Java has a built-in package for storing and organizing data in a computer. like Linked List,
Stack, Queue and array are few examples of java data structures.

● DATA CASTING - Type casting is a way of converting data from one data to another data type. It
is also known as DATA CONVERSION/TYPE CONVERSION/ TYPE COERCION.

● PRIMITIVE DATA TYPE - Predefined in Java.


Non-Primitive types
- are created by the programmer and are not defined by JAVA (except for String).
-used to call methods to perform certain operations, while primitive types cannot.

MODULE 3: CONCEPTS OF DATA STRUCTURE


The facebook algorithm determines which posts people see every time they open their facebook, and what
placement of order those posts display or show up. Essentially, the facebook algorithm evaluates every post. The
posts are displayed depending on the user's engagements arranged in descending or in non-chronological order.

Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the
following characteristics
• Unambiguous − Algorithms should be clear and unambiguous. Each of its
steps (or phases), and their inputs/outputs should be clear and must lead to
only one meaning.
• Input − An algorithm should have 0 or more well-defined inputs.
• Output − An algorithm should have 1 or more well-defined outputs, and should
match the desired output.
• Finiteness − Algorithms must terminate after a finite number of steps.
• Feasibility − Should be feasible with the available resources.
• Independent − An algorithm should have step-by-step directions, which should
be independent of any programming code.

Loops
-for
-do
-while

Flow-Control
-if statements

Algorithm writing is a process and is executed after the problem domain is


well-defined. That is, we should know the problem domain, for which we are designing
a solution.

Let's try to learn algorithm-writing by using an example.


Problem − Design an algorithm to add two numbers and display the result.

Step 1 − START
Step 2 − declare three integers a, b & c
Step 3 − define values of a & b

Step 4 − add values of a & b

Step 5 − store output of step 4 to c


Step 6 − print c
Step 7 − STOP
ALGORITHM is arranged in chronological order to follow the order of the statements

public class Module3{

public static void main(String [] args){

int a,b,c;
a= 80; b = 80;
c = (a+b);

System.out.println(“Value of c is” + “ “ + c);

An math expression in Java is a combination of one or more operators(+,-,*,/, %,&& ||,


and many more) The result of calculation is the computation coming from the
operands. The operands might be numbers, but can represent other things like
characters, strings, boolean etc.

A method is a block of code which only runs when it is called. You can pass data
known as parameters into a method.

The answer is to reuse code: define the code once, and use it numerous times

The java math class has many methods.

examples of java built-in math method

Math.max(x,y) - This java math method is use to find the highest number between x and y

Math.min(x,y) - This java math method is use to find the lowest number between x and y

Math.sqrt(x) - Returns the square root of x

Math.abs(x) - Returns the absolute (positive) value of x

Math.random() - Returns a random number between 0.0(inclusive), and 1.0 (exclusive)

FINDING THE HIGHEST VALUE


HOW TO WRITE YOUR OWN IN MODEL IN JAVA?

MODULE 4: Algorithm analysis:Big-O Notation


1. Explain the Big-O Notation
2. Understand the time and space and time complexities
3. Apply Big-O in the program

Algorithm is a method or a process followed to solve a problem. A problem can have many
applicable algorithms and they vary depending on who is trying to create the solution, like a
programmer solving a machine problem.

Big O notation, and why does it matter to I.T

“Big O notation is a mathematical notation that describes the limiting behavior of a


function when the argument tends towards a particular value or infinity. It is a member of a
family of notations invented by Paul Bachmann, Edmund Landau, and others, collectively called
Bachmann–Landau notation or asymptotic notation.”

Big O notation describes the complexity of your code using algebraic terms

O(n²) = “Big O squared”

“n” = input size

Function: g(n) = n² inside the “O()” give us an idea of how the complex the
algorithm is with respect to the input size
● Every time we hear the performance of an algorithm, it describes using the Big O
Notation. The study of the performance of algorithms or algorithmic complexity -
falls into the field of algorithm analysis.
● Algorithm analysis answers the questions of how many resources, such as disk
space or time, an algorithm consumes. The less time spent by the algorithm to
complete the tasks, the better.

CONSTANT FUNCTION

Constant Time Algorithm - O(1)

Please check the aforementioned code, clearly, it doesn’t matter what n is, above. The
code takes a long time to execute. It is not dependent on the size of i.

Though it takes 3 times to run the input/display the results, it does not depend on the
size of the input, n. We indicate constant time algorithms as follows:

“Ang 3 statements na ito ay parehas lang”

O(1). Note that O(2), O(3) or even O(1000) would mean the same thing.

It’s not about how long it takes to run, only that, it takes constant time.
LOGARITHM FUNCTION

Logarithm Time Algorithm

There you have it! Our simple algorithm ran log(8) = 3 times.

LINEAR FUNCTION

Linear Time Algorithm

If it grows linearly, it grows directly proportional to the size of its inputs.

“Ilang beses ang loop nag” run? The answer is n times!

What we do know is that the simple algorithm presented above will grow linearly with the
size of its input.

We'd prefer a run time of 0.1n rather than (1000n + 1000), but both are still linear
algorithms; they both grow directly in proportion to the size of their inputs.
The runtime would still be linear in the size of its input, n. We indicate linear algorithms
as follows: O(n).

As with the constant time algorithms, we don't care about the specifics of the runtime.
O(2n+1) is the same as O(n), as Big O Notation concerns itself with growth for input
sizes.

1. Why is Big O commonly used?

In computer science, big O notation is used to classify algorithms according to


how their run time or space requirements grow as the input size grows. In other words,
it measures a function's time or space complexity. This means, we can know in advance
how well an algorithm will perform in a specific situation

2. Should I learn Big O notation?

Big O notation is an important tool for computer scientists to analyze the


cost of an algorithm. Most software engineers should have an understanding of
it.
MODULE 5: FREQUENCY OF
COUNTING
Frequency count

-Kept a tally of how often you do something over a certain span of time

Frequency count (or) Step count: It denotes the number of times a statement to be
executed. Generally, count value will be given depending upon corresponding
statements. For comments, declarations the frequency count is zero (0).

Control Structures

1. Straight-forward Structure - program instructions are executed from the top going
down without any iteration or test.
2. Decision Control Structure - program instruction uses conditional statements like
If, else statement, switch and ternary operators
3. Iterative Control Structure -loops like for, while and do while including the label
but is now considered primitive programming. Also call by reference or function
call can be associated with iterative.
4. Memory Allocation Structure -array or database application but will require
more sophisticated processes.

Let us create a case study that will find the frequency of each element in the array.
Arrays are variable with the same type but with different elements.

In this program, we have an array of elements to count the occurrence of each element.

One of the approaches to resolve this problem is to maintain one array to store the
counts of each element of the array.

Loop through the array and count the occurrence of each element as frequency and
store it in another array fr.

What is FREQUENCY COUNT IN JAVA?

The is the ALGORITHM

● STEP 1: START
● STEP 2: INITIALIZE arr[] ={1, 2, 8, 3, 2, 2, 2, 5, 1 }.
● STEP 3: CREATE fr[] of arr[] length.
● STEP 4: SET visited = -1.
● STEP 5: REPEAT STEP 6 to STEP 9 for(i=0;i<arr.length;i++)
● STEP 6: SET count = 1
● STEP 7: REPEAT STEP 8 for(j=i+1;j<arr.length;j++)
● STEP 8: if(arr[i]==arr[j]) then
count++
fr[j] =visited
● STEP 9: if(fr[i]!=visited) then
fr[i]=count
● STEP 10: PRINT "------------"
● STEP 11: PRINT "Element | Frequency"
● STEP 12: PRINT "-------------"
● STEP 13: REPEAT STEP 14 for(i=0;i<fr.length;i++)
● STEP 14: if(fr[i]!=visited) then
PRINT arr[i] and fr[i]
● STEP 15: PRINT "-------------"
● STEP 16: END
To write a frequency count, you need to understand the basics of loops.

Loops in Java is a feature used to execute a particular part of the program repeatedly if a
given condition evaluates to be true. While all three types' basic functionality remains the
same, there's a vast difference in the syntax and how they operate

Java provides three types of Loops: for, while, and do-while. Four Elements control
a loop: initialization expression(s), test expression, update expression, and
loop-body.
IN PYTHON:

list1 = [1, 2, 8, 3, 2, 2, 2, 5, 1]

frequent_number = 2 #input here

result = list_1.count(frequent_number)

print("frequency of data inside the list is"," ",result)

Let’s try another example in python, we are going to write a program that finds the frequency of
all the elements in an array/list.

This is the algorithm

● Initialize the array


● Initialize an empty dictionary
● Iterate over the list
○ If there is no element in the dictionary , set the value to 1
○ Otherwise increment the value by 1
● Display the elements and frequencies by iterating over the dictionary

# initializing the list


arr = [5,5,5,5,5,8,8,8,8,8,3,3,3,3,2,2,2,2]

# Initialize a variable for dictionary to store elements

elements_count = {}

#Create a loop to reference element in the list


for element in arr:

#Check if the element is present in the dictionary

if element in elements_count:
# add/or increment by 1
elements_count[element] += 1
else:
# set counter to 1
elements_count[element] = 1
# display the key pairs {key and value} dictionary style
for key, value in elements_count.items():
print(f"{key}: {value}")
This is the a algorithm using the Counter class

● Import the collections module


● Initialize the array.
● Assign a list to the Counter class.
● Store it in a variable result
● Print the element and the frequencies
● Iterate the frequency count

Code example in python

import collections

arr1 = [12,2,2,2,4,2,4]

deep = collections.Counter(arr1)

for key, value in deep.items():

print(f"{key}:{value}")

1. Is count the same as frequency?

The number of responses emitted during an observation period. Rate/frequency: A


ratio of count per observation time; often expressed as count per standard unit of time
(e.g., per minute, per hour, per day)

2. How to count the number of digits in an Integer?

public class Count {

public static void main(String[] args) {

int counter = 0, num1 = 123456;

for (; num1 != 0; num1 /= 10, ++counter) {


}

System.out.println("Number of digits: " + counter);


}
}
MODULE 6 :DATA TYPES AND
UNFOLDING ARRAYS
➔ In programming or in related communities data structure is very crucial to develop a
particular application, spectrum from data analytics to data intelligence.

➔ A data structure is a collection of data types which are stored and organized in such
a way that it allows for efficient access and modification.

➔ DATA TYPE or simply type is an attribute - Characteristics of data which tells the
compiler or interpreter how the data would be applied by the software engineer.

THINGS TO PONDER:

A data structure is a bit more complex – it's a way to organize and group different data
types together.

Use a data structure throughout your program to easily access and manipulate all the
different pieces of information it contains.

Basic data types are supported by most programming languages:

● Integer
● Floating-point numbers
● Characters
● boolean

Data type controls or regulates the value of an expression, like variable or function.

EXAMPLE: data1 is declared as int or integer. The int data type determines that the speed
variable can only contain integers
8 pre defined data types or what we call primitive data types in java

● Boolean
● byte
● short type
● int
● long type
● double type
● float type
● char type

Apply the boolean primitive data type here:

Convert the boolean data type to string. Call the valueOf() method of java.

ARRAY
● An array is a way to store a list of items. It's like a list or a collection of things, but it's
stored in a specific way that makes it easier to access and manipulate the items.
● The purpose of an array is to make it easier to work with large amounts of data.
Instead of having to keep track of a bunch of separate variables, you can use an
array to store all the related items together in one place. This makes it easier to access
and manipulate the items, and it can also make your code easier to read and
understand.

Ex. String [] favoriteColors ={Blue, Red, Violet, White, Black, Yellow};

Store names of 200 people then we can create an array of String types.

String[] data_rec = new String[200]; //statement has a limit of 200 , the number or value
of array is fixed.

Python declaration of an array/lists:

array1 = [1,2,3,4]

Java

int [] array1 = {1,2,3,4};


● In java, here is how we can declare an array.
dataType[] arrayName
● dataType - It can be primitive data types like int, char, double, byte, or java objects
arrayName - it is an identifier
● for example
double[] payment;

In this example this payment array can hold values of double type. But this is an ambiguous
statement of how many arrays can this variable hold.
“Ilang element ba nga array ang ma store or ma hold?”
To solve this problem, we need to allocate memory for the array in Java.
For example,
//Declare an array
double[] data1;
// allocate memory for the array
data1 = new double[10];

Next is to initialize the arrays during declaration.

For example,

// declare and initialize the array


int[] grade = {80,75,90,60};
We have created an array variable here the “grade” and we initialize it with values.

//declare an array

int [] grade = new int[4];


grade[0] = 80;
grade[1] = 75;
grade[2] = 90;
grade[3] = 60;

Arrays help maintain large sets of data under a single variable name to avoid confusion that
can occur when using several variables. Organizing data elements: Different array algorithms,
like bubble sort, selection sort and insertion sort, can help you organize various data
elements clearly and efficiently.

OBE Micro Projects(Case program)

This is a quick discussion in array, please review your arrays topic in your programming 2
module. Arrays can store different types of data in the container, if you are working on a
prototype to store the information as part of a stateless data(temporary storage) array is your
best alliance.

So! please check this quick lesson on arrays, using the push method of java.

The push method works similarly in Stack. Our target is to add or store the data inside the
stack.

Example of a mirror file.


import java.util.*;
public class Module6_push{
public static void main(String args[]){
// create a stack
Stack<String> s = new Stack<String>();
s.push("1. Cruz Juan");
s.push("2. Tan Pedro");
s.push("3. Silakbo Confesor");
s.push("4. Silak Moloy");
s.push("5. Bordloy Ramko");
// Print elements in stack
System.out.println("Stack Elements: " + s);
// Push new elements
s.push("6. Emanpalo Diretso");
s.push("7. Bukal Julyana");
// Stack after adding new elements
System.out.println("Stack after adding new elements " + s);
}
}
1. In the aforementioned program, invoke the Scanner class
1.1 Ask the user to enter the lastname and firstname
1.2 Use “student_name” as your identifier
2. push the new student_name in the stack
3. Display all the records

A Data type is one of the forms of a variable to which the value can be assigned of a given type
only. This value can be used throughout the program. A Data structure is a collection of data
of different data types. This collection of data can be represented using an object and can be
used throughout the program.

Arrays are classified into two types based on their dimensions : single-dimensional and
multi-dimensional. Logically, a single-dimensional array represents a linear collection of
data, and a two-dimensional array represents a mathematical matrix. Similarly, a
multidimensional array has multiple dimensions.

Key to corrections

1.Declare x as array and assign these elements -> {10,20,30,40}


2. Display the length of x
3. Read the content of the arrays, declare counter as a variable and count the
number of elements inside the array
3.1 Display the array
1. In the aforementioned program, invoke the Scanner class
1.1 Ask the user to enter the lastname and firstname
1.2 Use “student_name” as your identifier
2. push the new student_name in the stack
3. Display all the records
MODULE 8 : 2D & 3D ARRAYS
Multidimensional arrays are an extension of 2-D matrices and use additional sunscripts for
indexing. A 3-D array, for example, uses three subscripts. The first two are just like a matrix,
but the third dimension represents pages or sheet of elements.

1. Store 5 numbers -use programming's simple variable and data type concepts, then we
need five variables of int data type and the program will be as follows −

The code example is so simple, but if you have these hundreds of data, you won’t use that code
anymore. It can take up a large portion of your pc memory and it’s not fit for clean type
programming.

We can apply this example to resolve that problem.


Imagine a giant grid, stretching out as far as the eye can see. Each row and column is like a
street, and each cell is a house. That's what a 2D array looks like – a flat plane of
information, organized into rows and columns. It's a great way to store and manage data,
especially when you need to keep track of things in a specific order. Now, imagine adding
another dimension to that grid – a third layer that rises above the first two, like a towering
skyscraper. That's what a 3D array looks like – a stack of 2D arrays,stacked on top of each
other. It's like a cityscape, with rows and columns of houses stacked on top of each other,
reaching up into the sky. With a 3D array, you can store and manage even more data, and keep
track of it all in a precise and organize way.

MULTIDIMENSIONAL ARRAY is an array of arrays.

Example of 2 dimensional array that can hold a maximum of 12 elements:

Single array type of syntax:


int [] [] array1 = new int [3] [4];

Multiple Arrays:
2 dimensional arrays. It has 2 arrays as its elements.
Int [1] [3] num_Test = {{1,2,3,4,5}, {6,7,8,9,10}};
Change the value of the 2d arrays
The basic principle of programming is to understand the IPO, Input process and output part of
that game is to Write, Add, Retrieve and Display.

Alternative way to loop and display the contents of the arrays, mimicking the macro
scripts to make it easier for the learners. This time we will apply the for each loop.
Primer Test using the for loop

3D array is a multi-dimensional array just like the 2d arrays


3 subscripts:Block size, row size and column size.

You might also like