0% found this document useful (0 votes)
10 views12 pages

Data Structure - Jumail

Uploaded by

mmhalith3
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)
10 views12 pages

Data Structure - Jumail

Uploaded by

mmhalith3
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/ 12

1|Page

Data structure is the arrangement of data in a Abstract Data Type is a specification of


computer memory/storage. a mathematical set of data and the set
An algorithm is a step by step procedure for of operations that can be performed on
solving a problem in a finite amount of time. the data.
Many algorithms apply directly to a specific data Arrays are a group of continuous similar
structures. type of variables referred by a common
name.
Data structures are divided into two types:
Two types of arrays - *One-Dimensional
*Primitive data structures. Arrays *Multi-Dimensional Arrays
*Non-primitive data structures. Here is the syntax for arrays:
Primitive Data Structures are the basic data *1D Arrays: int arr [n];
structures that directly operate upon the *2D Arrays: int arr [m][n];
machine instructions. They have different *3D Arrays: int arr [m][n][o];
representations on different computers. Advantages of arrays:
*Fast access if index is known
Non-primitive data structures are more *Easy to add an element in a particular
complicated data structures and are derived from location.
primitive data structures. *Arrays avoid memory overflow
The non-primitive data structure is divided into Disadvantages of arrays:
two types: *Fixed size Same data type
*Linear data structure *Slow in searching an element
*Non-linear data structure *Slow in inserting/deleting an element
Linear Data Structure - in linear data structures, Multi-dimensional array can be
the elements are arranged in sequence one after considered as an array of arrays.
the other. Elements are arranged in particular
Pointer contains memory address of a
order; they are easy to implement.
particular type of data.
Type of Linear Data Structure In Java, a structure is not a built-in data
*Array Data Structure type like int, float, or String. However,
you can create your own custom data
*Stack Data Structure
types using classes and objects.
*Queue Data Structure
*Linked List Data Structure A class in Java is a blueprint for creating
Non-linear data structures are further divided objects (a particular data structure),
into graph and tree based data structures. providing initial values for state
(member variables or attributes), and
Types of non – linear
implementations of behavior (member
*Graph Data Structure
functions or methods).
* Trees Data Structure

Linear Data Structure Non - Linear Data Structure


All the items are present on the single layer. The data items are present at different layers.
The time complexity increase with the data Time same.
size.
Easy to implement. Difficult to implement.
2|Page

Collections in Java A linked list consists of nodes of data which are


*It is a Framework. it is providing as connected to other nodes.
Architecture to store and Common operations of Linked List are:
Manipulate the group of Object. initializeList() - initializes the list as empty list.
insertFirstElt (int elt) - inserts a new element into an
*it means a single unit of object
empty list.
Java Framework is readymade insertAtFront (int elt) - inserts an element at the
Architecture. Java Framework beginning of the list.
represents a set of class and insertAtEnd (int elt) - inserts an element at the end
interface. of the list.
Collection Framework - It is a insertAfter (int oldElt, int newElt) - inserts an
unified architecture for storing and element after a specified element.
manipulating a group of objects. deleteElt (int elt) - deletes a specified element.
Why use Java collection displayList () - displays all the elements in the list
*Reducing the effort required to isEmpty () - returns true if the list has no elements,
write the code by providing useful false otherwise.
data structures and algorithms. isFull () - returns false if the list is full, false otherwise.
*Unrelated APIs can pass collection Advantages of Linked List:
interfaces back and forth. *Easy to insert and delete elements.
*Decreases extra effort required to *Unlike array, memory space is not wasted in linked
learn, use, and design new API’s. list.
*Supports reusability of standard Disadvantages of Linked List: *Slow in searching.
Advantages of Generics
data structures and algorithms.
*Code Reuse: User can write a
Vector - It is dynamic array to used method/class/interface once and use it for any type
way to data store elements. It is user want.
same as Array List. Vector is *Type Safety: Generics make errors to appear
synchronized. compile time than at run time.

A dynamic array size assign at running


time. It can be automatic resizing. It Advantages of ArrayList
arrays expands as add more elements. So *Since the size is resized during the running
not need to determine the size ahead of time; it is easy during implementation
time. requirement changes.
Advantage of Dynamic Array *Can store and delete data randomly.
*Random Access of Elements. *Various types of Object can be entered.
*Good locality of reference and data Disadvantages of ArrayList
cache utilization. *If a data entry is added or removed from an
*Easy to Insert /delete at the time. arraybased list, the data must be transferred to
Disadvantage of Dynamic Array update the list.
*Waster more memory *In the worst case, for an array-based list with n
*Shifting elements is time consuming. Data insertions, additions, and deletions are
*Expanding /Shrinking the array is time O(n) Time.
consuming.
3|Page

Advantages of Data structures Queue is a data structure which is


*Data structure facilitates effective data storage in used to handle data in a first-in-first-
storage devices. out (FIFO) method. That is we can
*The use of data structures makes it easier to remove the element which has been
retrieve data from a storage device. added earlier from the queue first.
*Manipulation of vast amounts of data is simple
when a proper data structure technique is used. Common operations of Queue are:
initializeQueue()
Space complexity is the amount of memory used by initializes the queue as empty queue.
the algorithm (including the input values to the enqueuer ()
algorithm) to execute and produce the result. adds an element at the rear of the
Operation of Data Structure queue.
Traversal: Traversal operations are used to visit each dequeuer ()
node in a data structure in a specific order. removes and returns the front
Deletion: Deletion operations remove data element from the queue.
elements from a data structure. frontElt()
Search: Search operations are used to find a specific returns the front element without
data element in a data structure. removing it.
Sort: Sort operations are used to arrange the data
elements in a data structure in a specific order. isEmpty ()
Merge: Merge operations are used to combine two returns true if the queue has no
data structures into one. elements and false otherwise.
Copy: Copy operations are used to create a isFull()
duplicate of a data structure. returns true if the queue is full of
elements and false otherwise.
Application of Data Structure displayQueue()
Storage: Data structures facilitate efficient data displays all elements from front to rear.
persistence, like specifying attribute collections and
corresponding structures used in database Advantages of Queue:
management systems to store records. First-in-first-out access
Data Exchange: Organized information, defined by Disadvantages of Queue:
data structures, can be shared between applications Difficult to access other items
like TCP/IP packets.
Scalability: Big data applications rely on data Big-O notation represents the upper
structures to manage and allocate data storage bound of the running time of an
across many distributed storage locations. algorithm. Thus, it gives the worst-
case complexity of an algorithm.
Creating a structure to store ID, Name and gender
Omega notation represents the
of an Employee.
lower bound of the running time of an
Struct Employee {
algorithm. Thus, it provides the best
Int ID;
case complexity of an algorithm.
Char Name;
Char Gender
};
4|Page

A tree is a widely-used data structure that Binary Search Tree Operation


emulates a hierarchical tree structure with *Insertion
a set of linked nodes. A rooted tree has a *Deletion
distinguished node called root. *Searching
Tree Terminology and Basic Properties *Minimum
*Sibling *Ancestor *Maximum
*Descendant *Leaf. Advantages Binary Search Tree
*Subtree *Path of two nodes *BST is fast in insertion and deletion when
*Length of a path. balanced. It is fast with a time complexity of O
Tree Types (log n).
*Binary tree *BST is also for fast searching, with a time
complexity of O (log n) for most operations.
*Binary search trees
BST code is simple as compared to other data
1) A binary tree is a rooted tree in which no structures.
node can have more than two children, and Disadvantages Binary Search Tree
the children are distinguished as left and *The main disadvantage is that we should
right. always implement a balanced binary search
A full binary tree is a tree in which every
tree.
node other than the leaves has two
*A BST can be imbalanced or degenerated
children. which can increase the complexity.
A complete binary tree is a binary tree, *Do not support some operations that are
which is completely filled, with the possible possible with ordered data structures.
exception of the bottom level, which is
An AVL tree defined as a self-balancing BST
filled from left to right. where the difference between heights of left
A perfect binary tree is a binary tree with and right sub trees for any node cannot be
all leaf nodes at the same depth. All internal more than one.
nodes have degree 2. The difference between the heights of the left
sub tree and the right sub tree for any node is
known as the balance factor of the node.

What is sorting?
Arranging items in ascending or descending
order is called as sorting.
There are different types of sorting techniques
Advantages of Binary Tree: each of which is good for some cases such as
Quick search, Quick inserts, Quick deletes nearly sorted, reversed, random, etc.
(If the tree remains balanced)
Disadvantages of Binary Tree: What is search algorithm?
Deletion algorithm is complex A search algorithm is an algorithm for finding
2. Binary Search Tree: an item among a collection of items.
It is a binary tree such that for every node Sequential/Linear Search Algorithm:
N in the tree. It examines the first element in the list and
All keys in N's left sub tree are less than then second element and so on until a much is
the key in N, and All keys in N's right sub found.
tree are greater than the key in N.
5|Page

Why need Algorithm Analysis Briefly describe the enqueue and dequeue operations
Generally, there are multiple of the queue data structure using diagrams.
approaches to solve one problems 1.Enqueue (insert):
statement. Algorithm analysis is *Check if the queue is full.
performed to figure out which is *If the queue is full, produce overflow error and exit.
the better algorithms out of this *If the queue is not full increment rear point the next
options. empty space.
What is better algorithm *Add data element to the queue location where the
Faster time complexity rear is pointing.
Less Memory (Space Complexity
REAR FRONT
Easy to read
Less line of code
Before
How to Determine Best D C B A
Algorithm
1.Time Complexity D C B A After
2.Space Complexity
Time Complexity
REAR FRONT
It is amount of time taken by
algorithm to run. The input
2.Dequeue (insert):
processed by an algorithm helps in
*Check if the queue.
determine the time complexity.
*If the queue is empty produce under flow error and
Space Complexity
exit.
It is amount of memory or space
*If the queue is not empty access the data where front
taken by algorithm to run. The
is pointing.
memory required to process the
*Increment front pointer to point next available data
input by an algorithm helps in
element.
determining the space
complexity.
Asymptotic analysis helps in
evaluating performance of
Different Stack and Queue
an algorithm in terms of input size
Stack:
and its increase.
*Last in first out. (LIFO)
Rules of Big O (O) Notation
*Push, POP, Peek.
*Running PC it has single *Stack of plate.
processor assume
*It performs sequential Execution Queue:
of statements *First in first out. (FIFO)
*Assignment operation takes 1 *Enqueue, dequeuer, front.
unit of time *Queue in a grocery store.
*Return statement takes 1 unit of
time
*Arithmetical operation takes 1
unit of time
6|Page

Different between Array and Linked Difference between Linear and Non-linear Data
list ? Structures:
Array: Linear Data Structures:
*Providing direct access to any Elements are arranged in a linear or sequential
element using its index. order. Examples include arrays, linked lists, queues,
*making it less flexible in terms to
and stacks.
size adjustment.
Non-linear Data Structures:
Linked list:
*Utilizes noncontiguous memory Elements are not arranged in a sequential order.
locations. Examples include: trees and graphs. Non-linear
*Can dynamically adjust list sixe structures allow for more complex relationships
during runtime by adding or between elements.
removing node. Two Applications of LinkedList:
Memory Management:
Different between Singly Linked List Linked lists are used in dynamic memory allocation
and Doubly Linked list? where memory can be efficiently allocated and
Singly: Each node contains a data deallocated.
element next node. Implementation of Data Structures:
Double: Each node contains a data Linked lists are a fundamental building block for
element and references of both the implementing other data structures like stacks,
next previous nodes in the queues, and symbol tables.
sequences. Two Implementations of Queue Data Structure:
Best case efficiency is the minimum Using Arrays:
number of steps that an algorithm Elements are stored in an array, and two pointers
can take any collection of data (front and rear) are used to
values. maintain the queue.
Worst case efficiency is the Using Linked List:
maximum number of steps that an Nodes are linked, and pointers (front and rear)
algorithm can take for any collection indicate the start and end of
of data values. the queue.
Average case efficiency Difference between Perfect Binary Tree and Full
Is the efficiency averaged on all Binary Tree:
possible input. Must assume a Perfect Binary Tree:
distribution of the input. All levels are completely filled with nodes.
Abstract Data Types (ADTs): The number of nodes is 2^{h+1} – 12 h+1 −1
Abstract Data Types refer to high- Full Binary Tree:
level descriptions of data structures Every node has either 0 or 2 children.
that specify the behavior rather than No node has only one child.
the implementation details. They
define a set of operations that can be
performed on the data, without
specifying how these operations are
implemented. Examples include
stacks, queues, lists, and trees.
7|Page

Two Advantages of Using Tree Data A program to search and replace an


Structure: element in an array java:
Efficient Searching and Sorting: public class Main {
Trees provide efficient searching and public static void main(String[] args) {
sorting operations due to their hierarchical int [] array = {1, 2, 3, 4, 5};
structure. int searchElement = 3;
Hierarchical Representation:
Trees are well-suited for representing int replaceElement = 10;
hierarchical relationships between
elements, making them useful in file for (int i = 0; i < array.length; i++) {
systems, organization structures, etc. if (array[i] == searchElement) {
Difference between Searching and Sorting: array[i] = replaceElement;
Searching: }
Involves finding a specific element in a data }
structure. for (int i = 0; i < array.length; i++) {
Sorting: System.out.println("Element at
Involves arranging elements in a specific index " + array [i] );
order (e.g., ascending or descending). } } }

Here is an example of a simple class in Java:


public class Car {
private String color; A program to store and print elements in
private String model; a two dimensional array java:
private int year; public class Main {
public static void main ( String [] args) {
public Car(String color, String model, int year) int [] [] array = {
{ {1, 2, 3},
this.color = color; {4, 5, 6},
this.model = model; 7, 8, 9}
this.year = year; } };
public String getColor() {
return color; } for (int i = 0; I < array.length; I++) {
public String getModel() { for (int j = 0; j < array[i].length; j++ )
return model; } {
public int getYear() { System.out.println
return year; } ("Element" + array [i] [j] ) ;
public void setColor(String color) { }
this.color = color; } }
public void setModel(String model) { }
this.model = model; }
}
public void setYear(int year) {
this.year = year;
}
}
8|Page

Write a java program that stores the given marks of the student and display the average
mark of each student. Use 2D array to store the subject marks. Mathematics Science
75 62 88 85 82 90

public class StudentMarks {


public static void main(String[] args) {
int[][] marks = { {75, 62, 88}, {85, 82, 90} };

for (int i = 0; i < marks.length; i++ ) {


int sum = 0;
System.out.print ("Student " + (i + 1) + " Marks: ");
for (int j = 0; j < marks[i].length; j++) {
System.out.print (marks[i][j] + " ");
sum += marks[i][j];
}
double average = (double) sum / marks [i].length;
System.out.println ("Average Mark for Student " + (i + 1) + ": " + average);
System.out.println ( );
}
}
}

Write a java code that calculate and returns the sum of all the even numbers of a given
array.
public class SumOfEvenNumbers {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sumOfEvenNumbers = calculateSumOfEvenNumbers(numbers);
System.out.println("Sum of Even Numbers: " + sumOfEvenNumbers);
}
public static int calculateSumOfEvenNumbers(int[] array) {
int sum = 0;
for (int number : array) {
if (number % 2 == 0) {
sum += number;
}
}
return sum;
}
}
9|Page

Write a java code for find the maximum and minimum elements in the following array.
78, 65,12, 48, 27, 86
public class FindMaxMin {
public static void main(String[] args) {
int[] numbers = {78, 65, 12, 48, 27, 86};
int max = findMax(numbers);
int min = findMin(numbers);
System.out.println("Maximum Element: " + max);
System.out.println("Minimum Element: " + min);
}
public static int findMax(int[] array) {
int max = array[0];
for (int number : array) {
if (number > max) {
max = number;
}
}
return max;
}
public static int findMin(int[] array) {
int min = array[0];
for (int number : array) {
if (number < min) {
min = number; Write java code to reverse the inserted string
} using a for loop.
} Note: Reverse string of "Hello" would be "olleH"
return min;
} public class ReverseString {
} public static void main(String[] args) {
String original = "Hello";
String reversed = reverseString(original);
System.out.println("Original String: " + original);
System.out.println("Reversed: " + reversed);
}

public static String reverseString (String input) {


int length = input.length();
StringBuilder reversed = new StringBuilder();
for (int i = length - 1; i >= 0; i--)
{
reversed.append(input.charAt(i));
}
return reversed.toString();
}
}
10 | P a g e

Write java code to display the subtraction of the matrices A and B


given below.
A = 1, 2, 3, 4 B = 10, 20, 30, 40
Note: Subtraction of A and B is A-B.
public class MatrixSubtraction {
public static void main(String[] args) {
int[][] A = {{1, 2}, {3, 4}};
int[][] B = {{10, 20}, {30, 40}};
int[][] result = subtractMatrices(A, B);
System.out.println("Resultant Matrix (A - B):");
displayMatrix(result);
}
public static int[][] subtractMatrices (int[][] A, int[][] B) {
int rows = A.length;
int cols = A[0].length;
int[][] result = new int[rows][cols];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
result[i][j] = A[i][j] - B[i][j];
}
}
return result;
}
public static void displayMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); Write java code to create the following array
} and display it on the screen. (Hint: consider the
} pattern of the data set when creating it)
}
2 4 6 8 10 12 14

public class DisplayArray {


public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10, 12, 14};
System.out.println("The array elements are:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
11 | P a g e

 Stack Algorithm

Push Algorithm for Stack Pop Algorithm for Stack


Void Push(item) Void Pop()
{ {
If (stack is full) If ( stack is empty)
print “ stack over flow” print” stack under flow”
else Else {
Increment top ; Stk[top] = Null;
Stack [top]= item; Decrement top ;
} }

Display Algorithm for Stack


Void Display()
{
If (stack is empty)
{
print” no element to display no element to display”
} else {
for i= top to 0 step -1 Print satack [i];
}
boolean isEmpty(){ if(top<= -1){ returnr true ;
}
else returnfalse ;
}
boolean isFull() { boolean isFull()
{
if(top>=SizeofArray-1) return
true ; else return false;
}
12 | P a g e

 Queue Algorithm

Insert Algorithm for Queue Display Algorithm for Delete Algorithm for Queue
Insert (item) Queue {
{ { If front = rear
If rear = max -1 then If front=rear print “queue is empty”
print “ queue is full” print “queue is empty “
else else
{ else Increment front
Increment rear For i = front to rear Array[front]= NULL;
Queue [rear]=item; Print queue [i]; }
} }

Pseudo code Algorithm for bubble sort


bubblesort (data[])
for(i=0,i<data.length-1;i++)
for(j=data.length-1;j>i;- - j)
swap elements in positions j and j-1 if they out of order;

Binary search Algorithm


Binary search pseudocode
Algorithm binarySearch (a, first, last, desiredItem)
binary search array a for value i:
mid = (first + last)/2 // approximate midpoint
if all elements have been searched,
if (first > last)
result is -1.
return false
else if (desiredItem equals a[mid]) examine middle element a[mid].
return true if a[mid] equals i,
else if (desiredItem < a[mid]) result is mid.
return binarySearch(a, first, mid-1, desiredItem) if a[mid] is greater than i. binary
else // desiredItem > a[mid] search lower half of a for i.
return binarySearch(a, mid+1, last, desiredItem)
if a[mid] is less than i, binary search
upper half of a for i.

You might also like