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

Data Structure and Algorithm Analysis - 2023-2024

The document discusses Java data structures including arrays and linked lists. Arrays have fixed size while linked lists have dynamic size. The document provides examples of implementing one dimensional, two dimensional and three dimensional arrays as well as adding, accessing and removing elements from a linked list.

Uploaded by

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

Data Structure and Algorithm Analysis - 2023-2024

The document discusses Java data structures including arrays and linked lists. Arrays have fixed size while linked lists have dynamic size. The document provides examples of implementing one dimensional, two dimensional and three dimensional arrays as well as adding, accessing and removing elements from a linked list.

Uploaded by

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

Abdelmalek Essaadi University

Java Data Structure

GCyB - I

Pr. Youssef SBAYTRI 2023-2024


Content
I-Introduction

II- Java collection framework

III- Algorithm analysis

IV- Implementation of data structure

V- Searching algorithms

VI- Sorting algorithms

VII- Recursive algorithms


2
I- Introduction

3
1. Why studying data structure ?

• The study of data structures helps us to understand the basic concepts involved in organizing and
storing data as well as the relationship among the data sets.

• Data structure provides a way to store and organize data in a manner that allows for efficient retrieval
and modification.

• Choosing the right data structure can significantly impact the performance of an application or
algorithm. This enable faster processing and reduced memory consumption (more details in Chapter
IV).

• Data structures are supported by the majority of programming languages, including C, C++, Java,
Python, and others.

• Java provides a rich set of built-in data structures through its libraries (Chapter II). 4
2. Goals of data structure

• Data structure implements two complementary goals.

Correctness Efficiency

Data structure is designed It should process the data at high


such that it operates speed without utilizing much of
correctly for all kinds of the computer resources such as
input memory space.

5
3. Classification of data structure

Depending on the organization of the elements, data structures are classified into two categories :
• Primitive data structure: Primitive data structures consist of the numbers and the characters which
are built in programs. These can be manipulated or operated directly by the machine level instructions.
Basic data types such as integer, real, character, and Boolean come under primitive data structures.

• Non-primitive data structure: Non-primitive data structures are those that are derived from primitive
data structures. These data structures cannot be operated or manipulated directly by the machine level
instructions. In java, non-primitive data structure further divided into:
• Linear data structures: Data elements are accessed in a sequential order but it is not compulsory
to store all elements sequentially (Ex: Array, Linked Lists, Stacks and Queues).

• Non-linear data structures: Data elements are not arranged in a sequential order. There is a
hierarchical relationship between individual data items (Ex: Trees and Graphs).
6
3. Classification of data structure

7
4. Abstract Data Type ?

• Abstract Data Types (ADT) is the combination of data structure with their operations.

• An ADT consists of two parts: Declaration of data and declaration of operations.


➢ For the primitive data structure (int, float, double), the system provides the implementation of
basic operation such as addition and substruction.
➢ For non-primitive data structure, operations should be defined. The implementation for these
operations can be done when we want to actually use them. That means, in general, user defined
data structure along with their operations.

8
2. Abstract Data Type

Properties off ADTs

• The operations of an ADTs are separated from their implementation (The same operation or
functionality can result from different implementations).

• ADTs are language-independent representations of data types (Can be used to specify a new data type
that can then be implemented in various ways using different programming languages).

• In Object-oriented language, classes are language-specific structures that allow implementation of


ADTs.
▪ A given ADTs can be implemented in different ways using different classes (Ex: Stack, Queue,
LinkedList can be implemented in different ways).
▪ A given class can in fact be used to represent more than one ADTs (a Java class ArrayList can
be used to represent a Stack, Queue and other ADTs). 9
II- Java Collection Framework

10
1. Arrays
• Array is a type of data structure that stores data elements of same data types in adjacent locations.

• The array’s length is set when the array is created, and it cannot be changed.

• Array index values must be integers in the range 0...length –1.

public class ArrayMethod1 { public class ArrayMethod2 {


public static void main(String[] args) { public static void main(String[] args) {
int[] arr = new int[6]; int[] arr ={7,15,103,45,23,31};
arr[0] = 7; }
arr[1] = 15; }
arr[2] = 103;
arr[3] = 45;
arr[4] = 23;
arr[5] = 31; Index 0 1 2 3 4 5
}
} Arr 7 15 103 45 23 31
11
1. Arrays
Arrays can be classified according to their dimension into:

➢ One-dimensional Array: It has only one row of elements. It is stored in ascending storage location.

➢ Two-dimensional Array: It consists of multiple rows and columns of data elements. It is also called
as a matrix.

➢ Multidimensional Array: Multidimensional arrays can be defined as array of arrays.


Multidimensional arrays are not bounded to two indices or two dimensions. They can include as
many indices as required.

12
1. Arrays
• Example of a 2D array (3x3) of integers

int[][] Array2D = {
{7, 12, 31},
{14, 62, 49},
{10, 55, 75}
};

// Accessing elements of the 2D array


System.out.println("Element at row 1, column 2: " + Array2D[0][1]);
System.out.println("Element at row 2, column 3: " + Array2D[1][2]);

13
1. Arrays
• Example of a 3D array (2x3x4) of integers

int[][][] Array3D = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} },
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};

// Accessing elements of the 3D array


System.out.println("Element at layer 1, row 2, column 3: " + Array3D[0][1][2]);
System.out.println("Element at layer 2, row 3, column 4: " + Array3D[1][2][3]);
14
1. Arrays
• JAVA standard arrays are of fixed length. Sometime we do not know how much memory we need so
we create a bigger size array. There by wasting space.

• If an array is already full and we want to add more values to it than we need to create a new array,
which have sufficient space and then copy the old array to the new array.

• To avoid this manual reallocation and copy we can use ArrayList or Linked Lists to store data.

15
2. Linked List
• A linked list is a dynamic data structure in which memory is allocated at run time.
• A linked list is considered as a chain of records called nodes. Each node in the list contains two
items: the data and a reference to the next node
• A linked list has the following properties.
➢ The number of nodes in a list is not fixed and can grow and shrink on demand.
➢ The last node has a reference to null.
➢ The entry point into a linked list is called the head (the reference to the first node) of the list.
➢ If the linked list is empty then the head is a null reference.

16
2. Linked List
import java.util.LinkedList;
LinkedList<Integer> LL = new LinkedList<>(); //Creating a linkedlist
LL.add(10); // Adding elements to the LinkedList
LL.add(20);
System.out.println("LinkedList elements: " + LL); // Displaying the elements of the LinkedList
System.out.println("the first element: "+LL.getFirst()); //get the first element
System.out.println("the second element: "+LL.get(1)); //get the second element
LL.addFirst(5); // Inserting at the beginning
System.out.println("the first element: "+LL.getFirst());
LL.addLast(50); // Inserting at the end
System.out.println("After insertion: " + LL);
LL.removeFirst(); // Removing the first element
LL.removeLast(); // Removing the last element
System.out.println("After deletion: " + LL);
boolean contains30 = LL.contains(30); // Searching
System.out.println("Does the list contain '30'? " + contains30);
System.out.println("Elements of the LinkedList:"); // Traversal
for (int number : LL) {
System.out.println(number); 17
}
2. Linked List

Applications:

➢ Implementing stacks, queues, binary trees and graphs of predefined size.

➢ Implement dynamic memory management functions of operating system. They can be used to
maintain a list of free memory blocks, allowing the operating system to efficiently allocate memory to
processes as needed.

➢ Linked lists can represent polynomials efficiently. Each node of the linked list can store a term of the
polynomial (e.g., coefficient and exponent), allowing for operations such as addition, subtraction,
multiplication, and division of polynomials.

18
2. Linked List
Advantages of Linked List:

➢ Dynamic Data Structure: Linked List being a dynamic data structure can shrink and grow at the runtime by deallocating or
allocating memory, so there is no need for an initial size in linked list.

➢ No Memory Wastage: As the size of a linked list can grow or shrink at runtime, so there is no memory wastage. Only the
required memory is allocated.

➢ Implementation: data structures like queues and stacks can be easily implemented using a Linked List.

➢ Insertion and Deletion Operation: In a Linked List, insertion and deletion operations are quite easy, as there is no need to
shift every element after insertion or deletion. Only the address present in the pointers needs to be updated.

19
2. Linked List
Disadvantages of Linked List:

➢ Slower Access Time: Accessing elements in a linked list requires traversing the list from the beginning (or end) to the
desired position, which can result in slower access times.

➢ Extra Space for Pointers: Linked lists require additional space for storing pointers/references to the next node, which
increases the overall space complexity of the data structure. This overhead can become significant, especially for large lists
or in scenarios where memory usage is critical.

➢ Difficulty in Reversal and Traversal: Singly linked lists can be traversed in only one direction, doubly linked lists support
traversal in both directions but require more memory for storing additional pointers.

➢ Potential for Fragmentation: Linked lists can suffer from memory fragmentation over time, especially in dynamic memory
allocation scenarios. As nodes are dynamically allocated and deallocated, memory fragmentation may occur, leading to
inefficient memory utilization and increased memory management overhead.
20
2. Linked List
• Types of Linked List:
➢ Singly Linked List: In a singly linked, each node has some data and a pointer to the next node in the list.

➢ Doubly Linked List: In a doubly linked list each node contains two pointer: one points to the previous node and the
other points to next node. This allows easy traversal in both forward and backward direction.

➢ Circular Linked List: In a circular linked list, the last node points to the first node. This implies that the list can be
traversed infinitely in a loop. Circular linked lists can be implemented using either singly linked nodes or doubly linked
nodes.

21
3. Stacks
• A stack is a linear data structure in which insertion and deletion of elements are done at only one
end, which is known as the top of the stack.
• Stack is called a last-in, first-out (LIFO) structure because the last element which is added to the
stack is the first element which is deleted from the stack.

22
3. Stacks
➢ When an element is inserted in a stack, the concept is called push.

➢ when an element is removed from the stack, the concept is called pop.

➢ Trying to pop out an empty stack is called underflow.

➢ Trying to push an element in a full stack is called overflow.

23
2. Stacks

import java.util.Stack;
public class StacksDemo
{
public static
void main(String[] args) {
Stack<Integer> ST = new Stack<Integer>();
// Pushing elements onto the stack
ST.push(1);
ST.push(2);
ST.push(3);
System.out.println("Stack: "+ST); ); // Displaying the elements of the Stacks
System.out.println("Stack size : "+ST.size()); //Returns the number of elements stored in the stack
System.out.println("Stack top : "+ST.peek()); // Peeking the top element of the stack
System.out.println("Stack pop : "+ST.pop());//Remove the top element of the stack
System.out.println("Stack top : "+ST.peek());
System.out.println("Stack isEmpty : "+ST.isEmpty()); //Verify if the stack is emptyt
}
} 24
3. Stacks
Applications:
➢ Depth-first search of trees and graphs traversal.

➢ Managing function calls and recursion in programming.

➢ Backtracking Algorithms: The backtracking algorithm uses stacks to keep track of the states of the problem-solving
process. The current state is pushed onto the stack, and when the algorithm backtracks, the previous state is popped
from the stack.

➢ UNDO and REDO operation: Undo/Redo operations: Each time an action is performed, it is pushed onto the stack.
To undo the action, the top element of the stack is popped.

➢ Browser history: manage the history of visited pages in web browsers. Each time you visit a new page, the URL is
pushed onto the stack, and when you hit the back button, the previous URL is popped from the stack.

25
3. Stacks
Advantages of stacks:

➢ Easy implementation: Stack data structure is easy to implement using arrays or linked lists, and its operations are simple to
understand and implement.

➢ Efficient memory utilization: Stack uses a contiguous block of memory, making it more efficient in memory utilization as
compared to other data structures.

➢ Fast access time: Stack data structure provides fast access time for adding and removing elements as the elements are
added and removed from the top of the stack.

26
3. Stacks
Disadvantages of stacks:

➢ Limited capacity: Stack data structure has a limited capacity as it can only hold a fixed number of elements. If the stack
becomes full, adding new elements may result in stack overflow, leading to the loss of data.

➢ No random access: Stack data structure does not allow for random access to its elements, and it only allows for adding and
removing elements from the top of the stack. To access an element in the middle of the stack, all the elements above it must
be removed.

➢ Memory management: Stack data structure uses a contiguous block of memory, which can result in memory fragmentation
if elements are added and removed frequently.

➢ Not suitable for certain applications: Stack data structure is not suitable for applications that require accessing elements
in the middle of the stack, like searching or sorting algorithms.

➢ Stack overflow and underflow: Stack data structure can result in stack overflow if too many elements are pushed onto the
27
stack, and it can result in stack underflow if too many elements are popped from the stack.
4. Queue
• A queue is an ordered list in which the elements in a queue are added at one end called the “rear”
and removed from the other end called the “front”.
• The first element to be inserted is the first one to be deleted. Hence, it is called First in First out
(FIFO).

28
4. Queue

import java.util.ArrayDeque;
public class QueueDemo
{
public static
void main(String[] args) {
ArrayDeque<Integer> que = new ArrayDeque<Integer>();
que.add(1);
que.add(2);
que.add(3);
System.out.println("Queue "+que);
System.out.println("Queue size : "+que.size());
System.out.println("Queue peek : "+que.peek());
System.out.println("Queue remove : "+que.remove());
System.out.println("Queue isEmpty : "+que.isEmpty());
}
}
29
4. Queue
Applications:
➢ Operating System Scheduling: In an operating system, queues are used to schedule processes and
allocate resources.
➢ Computer Networks: Queues are also used in computer networks to manage network traffic.
➢ Simulation and Modeling: Queues are commonly used in simulation and modeling to simulate real-
life scenarios. For example, a queue can be used to simulate the waiting time at a supermarket
checkout counter.
➢ Traffic Management Systems: Queues are used in traffic management systems to manage traffic
flow and avoid congestion.

30
4. Queue

Advantages of queue:

➢ Queues are easy to implement and understand.

➢ They are efficient for storing and accessing elements in a specific order.

➢ Queues are suitable for applications that require processing elements in a FIFO manner.

Disadvantages of queue:

➢ Queues have a fixed size, which means they can’t accommodate more elements than their size.

➢ Adding and removing elements from the middle of the queue is not efficient and requires shifting all the
elements.

31

You might also like