0% found this document useful (0 votes)
13 views

Data Structures and Algorithms

The document discusses data structures and algorithms. It defines data structures and common ones like arrays and linked lists. It also defines algorithms and how to analyze them in terms of time and space complexity. Characteristics and applications of various data structures are provided.

Uploaded by

Pweal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Data Structures and Algorithms

The document discusses data structures and algorithms. It defines data structures and common ones like arrays and linked lists. It also defines algorithms and how to analyze them in terms of time and space complexity. Characteristics and applications of various data structures are provided.

Uploaded by

Pweal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Data Structures and Algorithms

✘ By
✘ Engr. Isi Edeoghon
Compiled by Isi Edeoghon

What is a Data Structure?

✘ This refers to a way in which to arrange data in computers

Why the need for Data Structures?

✘ To enable ease of data searching


✘ To optimize Computer processing operations (Speed up)
✘ To enable numerous data requests
Compiled by Isi Edeoghon

What is an Algorithm?

An Algorithm is a step-by-step procedure, that sets out a set of instructions to be followed in


a specific order to get an output. Algorithms are independent of programming languages

Categories of Algorithms?
✘ Search − Algorithm to search an item in a data structure.
✘ Sort − Algorithm to sort items in a certain order.
✘ Insert − Algorithm to insert item in a data structure.
✘ Update − Algorithm to update an existing item in a data structure.
✘ Delete − Algorithm to delete an existing item from a data structure.
Compiled by Isi Edeoghon

Characteristics of Algorithms

Not all procedures can be called an algorithm. An algorithm should have the following characteristics −
✘ Unambiguous − Algorithm 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.
Compiled by Isi Edeoghon

Method of Writing an Algorithm


✘ We design an algorithm to get a solution to a given problem. A problem can be solved in
more than one way.

✘ Hence, many solution algorithms can be derived for a given problem. When this is done,
we analyze the proposed solution algorithms and implement the most suitable solution.
Compiled by Isi Edeoghon

How to Analyze an Algorithm?


✘ Efficiency of an algorithm can be analyzed at two different stages, before implementation and after
implementation. They are the following −

✘ A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm is


measured by assuming that all other factors, for example, processor speed, are constant and have no
effect on the implementation.

✘ A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm is


implemented using programming language. This is then executed on target computer machine. In this
analysis, actual statistics like running time and space required, are collected.
Compiled by Isi Edeoghon

Algorithm Complexity

✘ Suppose X is an algorithm and n is the size of input data, the time and space used by the
algorithm X are the two main factors, which decide the efficiency of X.

✘ Time Factor − Time is measured by counting the number of key operations such as
comparisons in the sorting algorithm.

✘ Space Factor − Space is measured by counting the maximum memory space required
by the algorithm.

The complexity of an algorithm f(n) gives the running time and/or the storage space
required by the algorithm in terms of n as the size of input data.
Compiled by Isi Edeoghon

Space Complexity

✘ Space complexity of an algorithm represents the amount of memory space required by the algorithm in its life cycle. The space
required by an algorithm is equal to the sum of the following two components −
✘ A fixed part that is a space required to store certain data and variables, that are independent of the size of the problem. For
example, simple variables and constants used, program size, etc.
✘ A variable part is a space required by variables, whose size depends on the size of the problem. For example, dynamic memory
allocation, recursion stack space, etc.
✘ Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is the variable part of the algorithm, which
depends on instance characteristic I. Following is a simple example that tries to explain the concept −

✘ Algorithm: SUM(A, B)
✘ Step 1 - START
✘ Step 2 - C ← A + B + 10
✘ Step 3 - Stop

✘ Here we have three variables A, B, and C and one constant. Hence S(P) = 1 + 3. Now, space depends on data types of given variables
and constant types and it will be multiplied accordingly.
Compiled by Isi Edeoghon

Time Complexity

✘ Time complexity of an algorithm represents the amount of time


required by the algorithm to run to completion. Time requirements can
be defined as a numerical function T(n), where T(n) can be measured as
the number of steps, provided each step consumes constant time.
Compiled by Isi Edeoghon

Types of Data Structures

✘ Array
✘ Linked List
✘ Stack
✘ Queue
✘ Binary Tree
✘ Binary Search Tree
✘ Heap
✘ Hashing
✘ Graph
Compiled by Isi Edeoghon

Arrays

✘ Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
✘ To declare an array in Java for instance, define the variable type with square
brackets:

int[] myNum = {10, 20, 30, 40};

✘ Here an array ”myNum”with data type integer is created containing 4 variables


Compiled by Isi Edeoghon

Characteristics of an Array
✘ Linear Data Structure
✘ Elements are stored in adjoining memory locations
✘ Elements can be accessed randomly using index
✘ Contains elements of similar data type

Syntax:
✘ Array declaration in Java:
datatype varname []=new datatype[size];
datatype[] varname=new datatype[size];
✘ Declaration and initialization together:

✗ Datatype varname [] = {element1, element2, element3, element4};


✘ 4 variables
Compiled by Isi Edeoghon

Accessing an Array

You access an array element by referring to the index number.


This statement accesses the value of the SECOND element in cars:
Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[1]);
// Outputs BMW
Compiled by Isi Edeoghon

Advantages of Arrays Disadvantages of Arrays


✘ Random access
✘ Easy sorting and iteration ✘ Size is fixed
✘ Replacement of multiple variables ✘ Difficult to insert and delete
✘ If capacity is more and occupancy less,
most of the array gets wasted
✘ Needs contiguous memory to get
allocated
Compiled by Isi Edeoghon

Applications of Arrays

✘ For storing information in a linear fashion


✘ Suitable for applications that require frequent searching
Compiled by Isi Edeoghon

Linked List
A linked list is a sequence of data structures, connected via links.
Each link contains a connection to another link.

✘ .
Compiled by Isi Edeoghon

Linked List

✘ Linked List contains a link element called first.


✘ Each link carries a data field(s) and a link field called next.
✘ Each link is linked with its next link using its next link.
✘ Last link carries a link as null to mark the end of the list
Compiled by Isi Edeoghon

Linked List

✘ A Linked List acts as a dynamic array and there is no need to specify size while
creating it, the size of the list automatically increases when items are added or
removed dynamically
Compiled by Isi Edeoghon

Creating a Linked List in Java Example

import java.util.LinkedList; // Import the LinkedList class


public class Main {
public static void main(String[] args) {
LinkedList<Type> varname = new LinkedList<Type>();

}
Compiled by Isi Edeoghon

Linked List Example


import java.util.LinkedList; // Import the engineeering.add(“CVE");
LinkedList class System.out.println(engineering);
public class Main { }
public static void main(String[] args) { }
LinkedList<String> engineering = new
LinkedList<String>();
engineeering.add(“CPE");
engineeering.add(“EEE");
engineeering.add(“MEE");
Compiled by Isi Edeoghon

Linked List Methods in Java


Method Description
addFirst() Adds an item to the beginning of the list.
addLast() Add an item to the end of the list
removeFirst() Remove an item from the beginning of the list.
removeLast() Remove an item from the end of the list
getFirst() Get the item at the beginning of the list
getLast() Get the item at the end of the list
clear() This method removes all of the elements from alist
Compiled by Isi Edeoghon

Linked List Example


~ Add this to the previous example as a continuation
…………..
engineering.remove(“EEE");
engineering.remove(3);
engineering.removeFirst();
engineering.removeLast();
System.out.println(engineering);
}
}
Compiled by Isi Edeoghon

Linked List Example


import java.util.LinkedList; // Import the engineeering.add(“CVE");
LinkedList class System.out.println(engineering);
public class Main { }
public static void main(String[] args) { }
LinkedList<String> engineering = new
LinkedList<String>();
engineeering.add(“CPE");
engineeering.add(“EEE");
engineeering.add(3, “And");
Compiled by Isi Edeoghon

Linked List Example


import java.util.LinkedList; // Import the engineeering.add(“CVE");
LinkedList class System.out.println(engineering);
public class Main { }
public static void main(String[] args) { }
LinkedList<String> engineering = new
LinkedList<String>();
engineeering.add(“CPE");
engineeering.add(“EEE");
engineeering.set(2, “And");
Iterating through the LinkedList Example
import java.util.LinkedList; // Import the LinkedList class }
}
public class Main { }
public static void main(String[] args) {
LinkedList<String> engineering = new LinkedList<String>();
engineeering.add(“CPE");
engineeering.add(“EEE");
engineeering.set(2, “And");
engineeering.add(“CVE");
System.out.println(engineering);
for (int i = 0; i < engineering.size(); i++) {
System.out.print(engineering.get(i) + " ");

Compiled by Isi Edeoghon


Compiled by Isi Edeoghon

Stack
✘ Stacks are abstractly equivalent to linked lists. They are used to model a
First-In-Last-Out (FILO), or Last-In-First-Out (LIFO) search method.
Compiled by Isi Edeoghon

Stack
✘ A stack can be implemented by means of Array, Structure, Pointer, and
Linked List. Stack can either be a fixed size one or it may have a sense of
dynamic resizing
Compiled by Isi Edeoghon

Stack in Java Basic Operations

✘ Stack operations may involve initializing the stack, using it and then de-initializing it. A
stack is also used for the following four primary operations −
✘ 4 major operations:

✘ push(ele) – used to insert element at top


✘ pop() – removes the top element from stack
✘ isEmpty() – returns true is stack is empty
✘ peek() – to get the top element of the stack

✘ All operations work in constant time i.e, O(1)


Compiled by Isi Edeoghon

Advantages

✘ Maintains data in a LIFO manner


✘ The last element is readily available for use
✘ All operations are of O(1) complexity

Disadvantages

✘ Manipulation is restricted to the top of the stack


✘ Not very flexible
Compiled by Isi Edeoghon

Creating a Stack in Java

✘ To create a stack, you must import java.util.stack package and use the
Stack() constructor of this class. The line below creates an empty Stack.

✘ Stack<E> stack = new Stack<E>();


Compiled by Isi Edeoghon

Pushing and Popping Elements in Java Stacks


Stack<Integer>();
import java.util.*;
import java.io.*;
// Use add() method to add elements
public class StackDemo { stack.push(10);
public static void main(String args[]) stack.push(15);
{ stack.push(30);
// Creating an empty Stack stack.push(20);
Stack<Integer> stack = new stack.push(5);
Compiled by Isi Edeoghon

(……………………………continued)
// Displaying the Stack
System.out.println("Initial Stack: " + stack);

// Removing elements using pop() method


System.out.println("Popped element: "
+ stack.pop());
System.out.println("Popped element: "
+ stack.pop());

// Displaying the Stack after pop operation


System.out.println("Stack after pop operation "
+ stack);
}
}
Compiled by Isi Edeoghon

Implementing a stack in Java using a Class


import java.io.*; {
import java.util.*; stack.push(i);
}
class Test }
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 5; i++)
Compiled by Isi Edeoghon
(……………………………continued)
// Popping element from the top of the stack
static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop Operation:");

for(int i = 0; i < 5; i++)


{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}
Compiled by Isi Edeoghon

(…………………………..continued) {
Integer pos = (Integer)
// Displaying element on the top of the stack stack.search(element);
static void stack_peek(Stack<Integer> stack)
{ if(pos == -1)
Integer element = (Integer) stack.peek(); System.out.println("Element not
found");
System.out.println("Element on stack
top: " + element); else
} System.out.println("Element is found
at position: " + pos);
// Searching element in the stack
}
static void stack_search(Stack<Integer>
stack, int element)
Compiled by Isi Edeoghon

Finally, the main program


✘ public static void main (String[] args)
✘ {
✘ Stack<Integer> stack = new Stack<Integer>();

✘ stack_push(stack);
✘ stack_pop(stack);
✘ stack_push(stack);
✘ stack_peek(stack);
✘ stack_search(stack, 2);
✘ stack_search(stack, 6);
✘ }
✘ }
Compiled by Isi Edeoghon

Output:

Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found
Compiled by Isi Edeoghon

Some methods used in stacks


Method Description
✘ peek() Returns the element on the top of the stack, but does not remove it.

✘ pop() Removes and returns the top element of the stack. An


‘EmptyStackException’ An exception is thrown if we call pop() when the invoking stack is empty.
✘ empty() It returns true if nothing is on the top of the stack. Else, returns false
✘ push(Object element) Pushes an element on the top of the stack.

✘ search(Object element) It determines whether an object exists in the stack. If the element is found,
It returns the position of the element from the top of the stack. Else, it returns -1.
Compiled by Isi Edeoghon

Queues
✘ Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends. One end is always used to insert
data (enqueue) and the other is used to remove data (dequeue). Queue
follows First-In-First-Out methodology, i.e., the data item stored first will
be accessed first.
Compiled by Isi Edeoghon

Some Queue Operations


✘ Queue operations may involve initializing or defining the queue, utilizing it, and then completely erasing it from the
memory. Here we shall try to understand the basic operations associated with queues −
✘ enqueue() − add (store) an item to the queue.
✘ dequeue() − remove (access) an item from the queue.

✘ Few more functions are required to make the above-mentioned queue operation efficient. These are −
✘ peek() − Gets the element at the front of the queue without removing it.
✘ isfull() − Checks if the queue is full.
✘ isempty() − Checks if the queue is empty.

✘ In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or storing) data in the
queue we take help of rear pointer.
Compiled by Isi Edeoghon

References
✘ Data Structures and Algorithms, Retrieved January 22 from
https://www.tutorialspoint.com/data_structures_algorithms/algorithms
_basics.htm
✘ Linked Lists Class/Stack Class, Retrieved January 25 from
https://www.geeksforgeeks.org/stack-class-in-java/
✘ Arrays/Linked List Retrieved January 29 from
✘ Data Structures & Algorithm using Java a Beginners Guide
Faizan Parvez , July 2020, FULLSTACK Development

You might also like