Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views36 pages

Unit 1

The document provides an overview of data structures, defining them as organized ways to store and manipulate data. It categorizes data structures into primitive and non-primitive types, as well as dynamic and static structures, and discusses various operations and characteristics associated with them. Additionally, it covers specific data structures like stacks, queues, linked lists, trees, and graphs, along with their implementations and applications.

Uploaded by

kkalyani
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)
6 views36 pages

Unit 1

The document provides an overview of data structures, defining them as organized ways to store and manipulate data. It categorizes data structures into primitive and non-primitive types, as well as dynamic and static structures, and discusses various operations and characteristics associated with them. Additionally, it covers specific data structures like stacks, queues, linked lists, trees, and graphs, along with their implementations and applications.

Uploaded by

kkalyani
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/ 36

Data Structures Unit-1 KHK

What is a data structure and explain different types of data


structures?
Data Structure:
Data Structure is a way of storing and organizing data in such a way that we can perform
operations on these data in an effective way
Data Structure= Organized Data + Allowed Operations
Data structure mainly specifies the following four things
 Organization of data
 Accessing methods
 Degree of associativity
 Processing alternatives for information
Types of Data structures:
The data structures are divided into two main categories
 Primitive data structures
 Non primitive data structures.

The data structures are also divided into two categories based on the type data they are
organizing
 Homogenous Data Structure
In homogenous data structure, all the elements are of same type. Example is
array.
 Non Homogenous Data Structure
In non-homogenous structures, all the elements are may or may not be of the
same types. Example is Records.

Vasavi Degree College 1


Data Structures Unit-1 KHK

Based on the memory allocated for the data the data structures are divided into
Dynamic Data Structure:
Dynamic Data Structure (DDS) refers to an organization or collection of data in memory
that has the flexibility to grow or shrink in size, allowing a programmer to control exactly
how much memory is utilized. Dynamic data structures change in size by having unused
memory allocated or de-allocated from the heap as needed.
Static Data Structure:
Static Data Structure is an organization or collection of data in memory that is fixed in
size. This results in the maximum size needing to be known in advance, as memory
cannot be reallocated at a later point. Arrays are a prominent example of a static data
structure.
Characteristics of a Data Structure
Correctness:
Data structure implementation should implement its interface correctly.
Time Complexity:
Running time or the execution time of operations of data structure must be as small as
possible.
Space Complexity:
Memory usage of a data structure operation should be as little as possible.

Operations on Data Structures: The operations involve in data structure are as follows.
Create: Used to allocate/reserve memory for the data element(s).
Destroy: This operation deallocate/destroy the memory space assigned to the specified
data structure.
Selection: Accessing a particular data within a data structure.
Update: For updation (insertion or deletion) of data in the data structure.
Searching: Used to find out the presence of the specified data item in the list of data
Sorting: Process of arranging all data items either in ascending or in descending order.
Merging: Process of combining data items of two different sorted lists of data items into
a single list.

Vasavi Degree College 2


Data Structures Unit-1 KHK

Stack
A stack is an ordered collection of items into which new items may be inserted and from which
items may be deleted at one end, called the TOP of the stack. It is a LIFO (Last In First Out) kind
of data structure.

Operations on Stack:
Push: Adds an item onto the stack. PUSH (s, i); Adds the item i to the top of stack.
Pop: Removes the most-recently-pushed item from the stack. POP (s); Removes the top element
and returns it as a function value.
Implementation of Stack: A stack can be implemented using two ways:
 Array
 Linked list.
Applications of Stack:
There are many applications of stack some of the important applications are given below.
 Backtracking
 Depth first Search
 Function Calls:
 Simulation of Recursive calls
 Expression Evaluation:
 Reversing a List
 Expression conversion
 Towers of Hanoi

Vasavi Degree College 3


Data Structures Unit-1 KHK

Queue
It is a non-primitive, linear data structure in which elements are added/inserted at one end
(called the REAR) and elements are removed/deleted from the other end (called the
FRONT). A queue is logically a FIFO (First in First Out) type of list.

Operations on Queue:
Enqueue:
Adds an item onto the end of the queue ENQUEUE(Q, i); Adds the item i onto the end of
queue.
Dequeue:
Removes the item from the front of the queue. DEQUEUE (Q); Removes the first
element and returns it as a function value.
Queue Implementation: Queue can be implemented in two ways.
 Static implementation (using arrays)
 Dynamic implementation (using painters)
Queue types:
 Circular Queue
 Double ended Queue
 Priority Queue
Applications of Queue:
 Breadth first Search
 CPU Scheduling
 Routing Algorithms
 Computation of shortest paths
 Computation a cycle in the graph
Linked Lists
Linked list is a special data structure in which data elements are linked to one another. Here,
each element is called a node which has two parts

Vasavi Degree College 4


Data Structures Unit-1 KHK

Info part which stores the information.


Address or pointer part which holds the address of next element of same type. Linked list is
also known as self-referential structure.

Operations on Linked Lists: The following operations involve in linked list are as given below
 Creation
 Insertion
 Deletion
 Traversing
Types of Linked Lists
 Singly Linked List:
 Doubly Linked List:
 Circular Linked List:
 Circular Doubly Linked List:

Trees
A tree can be defined as finite set of data
items called nodes. Tree is a nonlinear type of
data structure in which data items are
arranged in a sorted sequence. Trees
represent the hierarchical relationship
between various elements. The tree always
grown in length towards bottom in data
structure.

Vasavi Degree College 5


Data Structures Unit-1 KHK

Graphs

A graph G (V, E) is a set of vertices V and a set of edge E. An edge connects a pair of
vertices. Vertices in the graph are shown as point or circle and edges are drawn as arcs or
line segment.

Graph Representations: There are many ways of representing a graph:


 Adjacency List
 Adjacency Matrix
 Incidence list
 Incidence matrix
Explain About ADT ?
Abstract data types or ADTs are a mathematical specification of a set of data and the set
of operations that can be performed on the data. The actual implementation is not
defined, and does not affect the use of the ADT.
Users of an ADT are concerned with the interface, but not the implementation, as the
implementation can change in the future. ADTs implemented in programming languages
(or their libraries) include:
 List ADT
 Stack (last-in, first-out) ADT
 Queue (first-in, first-out) ADT
 Binary Search Tree ADT
 Priority Queue ADT
 Complex Number ADT (imaginary numbers)

Vasavi Degree College 6


Data Structures Unit-1 KHK

In Java, an ADT can be expressed by an interface, which is simply a list of method declarations,
where each method has an empty body. An ADT is recognized by a concrete data structure,
which is modeled in Java by a class. A class defines the data being stored and the operations
supported by the objects that are instances of the class. Also, unlike interfaces, classes specify
how the operations are performed in the body of each method.
Ex :
Stack ADT
interface stack
{
public Object pop();
public void push();
public Object peek();
public void display();
}

Advantages
Encapsulation:
The user does not need any technical knowledge of how the implementation works to use
the ADT. In this way, the implementation may be complex but will be encapsulated in a
simple interface when it is actually used.
Localization of change:
Code that uses an ADT object will not need to be edited if the implementation of the
ADT is changed, since any changes to the implementation must still comply with the
properties and abilities specified in the ADT definition.
Flexibility:
Different implementations of an ADT may be more efficient in different situations and it
is possible to use each in the situation where they are preferable. Hence this flexibility
increases the overall efficiency.
Implementation
Modern object-oriented languages, such as C++ and Java, support implementation of
ADT in the form of a class. You can use struct in C for the same.

Vasavi Degree College 7


Data Structures Unit-1 KHK

What is a Linked list explain types of linked lists?


A linked list or one way list is a liner collection of data elements, called nodes where the
linear order is given by means of references. That is each node is divided into to parts the
first part contains the information of the element and the second part called the link field
or next reference field, contains the address of the next node in the list.

The reference of the last node contains a special value called “NULL” reference denoted
by “ X” in the diagram signals the end of the list. The linked list also contains a first
pointer variable called “START” or “HEAD” which refer to the first node in the list . A
special case is the list that has no nodes, such list is called the “Null List” or “EmptyList”
and is denoted by null reference in the start variable.

Linked list can be classified as :


1. Singly liked list
2. Doubly linked list
3. Circularly singly linked list
4. Circularly doubly linked list

Operations:
We can perform the following operations on the linked lists
1. Traversing the list
2. Inserting a new node
3. Deleting a node from the list
4. Counting the number of nodes.

Vasavi Degree College 8


Data Structures Unit-1 KHK

Singly linked list:


Here in this type of list the node has only one reference variable apart from the
information part which always refers to the next node. In singly linked list we can
perform only forward traversing. This type of lists is also known as one way list.

Doubly linked list:


These types of lists are also known as two way list, which can be traversed in two
directions forward and backward directions. A two list is a collection of data elements
called nodes where each node is divided into three parts
 An information field INFO which contains the data
 A reference field “NEXT” which contains the location of the next node in the list.
 A reference field “PREV” which contains the location of the preceding node in
the list

Circularly Singly linked List:


In this type of lists the last node refers to the first node.

Circularly doubly linked list:


Here in this list the end node refer back to the header node and the header node refers to
the end node.

Vasavi Degree College 9


Data Structures Unit-1 KHK

Advantages using linked lists over arrays:


1. Linked lists provide flexibility in allowing items to be rearranged efficiently.
2. It is easier to insert or delete items by rearranging the links.
3. It provides polynomial manipulations.
4. It allows dynamic memory allocation.
5. It allows performing additions and subtractions multiplications on large size
numbers.
6. It provides implementations for the symbol table in compiler construction.
Disadvantages:
 Wastage of memory as pointers requirextra storage.
 Nodes are incontiguously stored thereby increasing time required to access
individual elements. To access nth item arrays need a single operation while linked
list need to pass through (n-1) items.
 Nodes must be read in order from beginning as they have inherent sequential
access.
 Reverse traversing is difficult especially in singly linked list. Memory is wasted
for allocating space for back pointers in doubly linked list.

What is a singly linked list? Write procedures for create, delete, insert
operations?
The singly linked list node consists of the information part and reference part which
refers to the next node.

Vasavi Degree College 10


Data Structures Unit-1 KHK

To refer the entire list we have “START” or HEAD and to refer last node “END”
reference variable.

1. Procedure to add an element at HEAD

a create a new node


Node nptr= new node(v,null);
b. check for existence of list
if(start== null)
{
Start = nptr;
End = nptr;
Size++;
}
c. if list is exist

start. Next = nptr ;

start=nptr;

2. Procedure to add at TAIL


a. Create a new node
Node nptr= new node(v,null);
b. Check for list existence

Vasavi Degree College 11


Data Structures Unit-1 KHK

if(start== null)
{
start = nptr;
end = nptr;
size++;
return;
}
c. If list is exist
end . link= nptr;
end = nptr;
3. Procedure to Delete at HEAD:
a. Check list is exist

if( start == null )

Print “list is empty “

Return;

b. // if list has only one element

If(start == end){

Start = null;

End= null;

Size--;

c. // if list has more than one node

Start = start . next;

Size--;

4. Procedure to delete at END


a. Check list is exist
if( start == null )
Print “list is empty “

Vasavi Degree College 12


Data Structures Unit-1 KHK

Return;
b. // if list has only one element
If(start == end)
{
Start = null;
End= null;
Size--;
}
c. // if list has more than one element
Node temp = start;
While( temp.link! = end)
temp= temp.link;
temp.link=null;
end =temp;
size--;
5. Procedure to insert at position
a. Create a new node
Node nptr= new noe(v,null)
b. Read the position to insert
pos=n;
if( pos > size)
print “ can’t insert an element “
c. //pos in between start and end
Node temp= start;
pos= pos-1;
for (i=1; i<size; i++)
{
If(i==pos)
{
nptr . link = temp;

temp . link = nptr;

Vasavi Degree College 13


Data Structures Unit-1 KHK

size++;
}
temp= temp . link;
}
6. To delete at position
a. If(start== null)
Print “list is empty “
b. If(pos> size)
Print “ position is out of range “;
Return;
c. node temp1, temp2;
temp1=start;
temp2= start;
for(i=1;i<size;i++)
{
if(i==pos)
{
temp2.link = temp1.link;
Size--;
return;
}
temp2=temp1;
temp1 temp1.link;
}
7. Display the list
a. If(start =null)
Print “ list is empty “
Return;
b. Node temp= start;
While(temp!=null)
{

Vasavi Degree College 14


Data Structures Unit-1 KHK

Print ( temp . data)


temp = temp . link;
}

Write a program to insert ,delete an node in asingle linked list


import java.util .Scanner;
class Node{
protected int data;
protected Node link;
public Node( ) /* Constructor */
{
link = null;
data = 0;
}
public Node(int d , Node n) /* Constructor */
{
data = d;
link = n;
}
public void setLink(Node n) /* Function to set link to next Node */
{
link = n;
}
public void setData (int d) /* Function to set data to current Node */
{
data = d;
}
public Node getLink( ) /* Function to get link to next node */
{
return link;
}

Vasavi Degree College 15


Data Structures Unit-1 KHK

public int getData( ) /* Function to get data from current Node */


{
return data;
}
}

/* Class linkedList */
class linkedList {
protected Node start;
protected Node end ;
public int size ;
public linkedList( ) /* Constructor */
{
start = null;
end = null;
size = 0;
}
public boolean isEmpty( ) /* Function to check if list is empty */
{
return start == null;
}
public int getSize( ) /* Function to get size of list */
{
return size;
}
public void insertAtStart(int val ) /* Function to insert an element at begining */
{
Node nptr = new Node(val, null);
size++ ;
if(start == null)
{

Vasavi Degree College 16


Data Structures Unit-1 KHK

start = nptr;
end = start;
}
else
{
nptr.setLink(start);
start = nptr;
}
}
public void insertAtEnd(int val) /* Function to insert an element at end */
{
Node nptr = new Node(val,null);
size++ ;
if(start == null)
{
start = nptr;
end = start;
}
else
{
end.setLink(nptr);
end = nptr;
}
}
public void insertAtPos(int val , int pos) /* Function to insert an element at position */
{
Node nptr = new Node(val, null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size; i++)
{

Vasavi Degree College 17


Data Structures Unit-1 KHK

if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink(nptr);
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
public void deleteAtPos(int pos) /* Function to delete an element at position */
{
if (pos == 1)
{
start = start.getLink();
size--;
return ;
}
if (pos == size)
{
Node s = start;
Node t = start;
while (s != end)
{
t = s;
s = s.getLink();
}
end = t;
end.setLink(null);
size --;

Vasavi Degree College 18


Data Structures Unit-1 KHK

return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
public void display( ) /* Function to display elements */
{
System.out.print("\nSingly Linked List = ");
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLink() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;

Vasavi Degree College 19


Data Structures Unit-1 KHK

System.out.print(start.getData()+ "->");
ptr = start.getLink();
while (ptr != null)
{
System.out.print(ptr.getData()+ "->");
ptr = ptr.getLink();
}
}
}
public class SinglyLinkedList /* Class SinglyLinkedList */
{
public static void main(String[ ] args)
{
Scanner scan = new Scanner(System.in);
linkedList list = new linkedList( ); /* Creating object of class linkedList */
System.out.println("Singly Linked List Test\n");
char ch;
/* Perform list operations */
do
{
System.out.println("\nSingly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
int choice = scan.nextInt();
switch (choice)
{
case 1 :

Vasavi Degree College 20


Data Structures Unit-1 KHK

System.out.println("Enter integer element to insert");


list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to insert");
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to insert");
int num = scan.nextInt() ;
System.out.println("Enter position");
int pos = scan.nextInt() ;
if (pos <= 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;

case 5 :
System.out.println("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");

Vasavi Degree College 21


Data Structures Unit-1 KHK

break;
default :
System.out.println("Wrong Entry \n ");
}
list.display( ); /* Display List */
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next( ).charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}

Write a program to perform insertion , deletion on “ Doubly linked list”


import java.util.Scanner;
class Node /* Class Node */
{
protected int data;
protected Node next, prev;
public Node( ) /* Constructor */
{
next = null;
prev = null;
data = 0;
}
public Node(int d, Node n, Node p) /* Constructor */
{
data = d;
next = n;
prev = p;
}
public void setLinkNext(Node n) /* Function to set link to next node */
{
Vasavi Degree College 22
Data Structures Unit-1 KHK

next = n;
}
public void setLinkPrev(Node p) /* Function to set link to previous node */
{
prev = p;
}
public Node getLinkNext( ) /* Funtion to get link to next node */
{
return next;
}
public Node getLinkPrev( ) /* Function to get link to previous node */
{
return prev;
}
public void setData(int d) /* Function to set data to node */
{
data = d;
}
public int getData( ) { /* Function to get data from node */
return data;
}
}
class linkedList /* Class linkedList */
{
protected Node start;
protected Node end ;
public int size;
public linkedList( ) /* Constructor */
{
start = null;
end = null;

Vasavi Degree College 23


Data Structures Unit-1 KHK

size = 0;
}
public boolean isEmpty( ) /* Function to check if list is empty */
{
return start == null;
}
public int getSize( ) /* Function to get size of list */
{
return size;
}
public void insertAtStart(int val) /* Function to insert element at begining */
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
}
size++;
}
public void insertAtEnd(int val) /* Function to insert element at end */
{
Node nptr = new Node(val, null, null);
if(start == null)
{

Vasavi Degree College 24


Data Structures Unit-1 KHK

start = nptr;
end = start;
}
else
{
nptr.setLinkPrev(end);
end.setLinkNext(nptr);
end = nptr;
}
size++;
}
public void insertAtPos(int val , int pos) /* Function to insert element at position */
{
Node nptr = new Node(val, null, null);
if (pos == 1)
{
insertAtStart(val);
return;
}
Node ptr = start;
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
}
ptr = ptr.getLinkNext();

Vasavi Degree College 25


Data Structures Unit-1 KHK

}
size++ ;
}
public void deleteAtPos(int pos) /* Function to delete node at position */
{
if (pos == 1)
{
if (size == 1)
{
start = null;
end = null;
size = 0;
return;
}
start = start.getLinkNext();
start.setLinkPrev(null);
size--;
return ;
}
if (pos == size)
{
end = end.getLinkPrev();
end.setLinkNext(null);
size-- ;
}
Node ptr = start.getLinkNext();
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node p = ptr.getLinkPrev();

Vasavi Degree College 26


Data Structures Unit-1 KHK

Node n = ptr.getLinkNext();
p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
public void display( ) /* Function to display status of list */
{
System.out.print("\nDoubly Linked List = ");
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLinkNext() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ " <-> ");
ptr = start.getLinkNext();
while (ptr.getLinkNext() != null)
{
System.out.print(ptr.getData()+ " <-> ");
ptr = ptr.getLinkNext();
}
System.out.print(ptr.getData()+ "\n");

Vasavi Degree College 27


Data Structures Unit-1 KHK

}
}

public class DoublyLinkedList /* Class DoublyLinkedList */


{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
linkedList list = new linkedList( ); /* Creating object of linkedList */
System.out.println("Doubly Linked List Test\n");
char ch;
do /* Perform list operations */
{
System.out.println("\nDoubly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to insert");
list.insertAtEnd( scan.nextInt() );
break;

Vasavi Degree College 28


Data Structures Unit-1 KHK

case 3 :
System.out.println("Enter integer element to insert");
int num = scan.nextInt() ;
System.out.println("Enter position");
int pos = scan.nextInt() ;
if (pos < 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
System.out.println("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
list.display( ); /* Display List */
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);

Vasavi Degree College 29


Data Structures Unit-1 KHK

} while (ch == 'Y'|| ch == 'y');


}
}

What is an array ? Explain algorithm for delete insert and search an element
in the array?
Array:
It is a linear data structure. It is a collection of finite set of similar data elements. An array
is finite because it contains only limited number of elements.
Ex:
An array of integers to store the age of all students in a class.
Int age[ ]= new int[50];
Index:
All the elements in an array can be referenced bya subscript like a[i] this subscript is
known as index. An index is always an integervalue starts from 0 and ends with size-1.
One dimensional array:
if only one subscript is required to reference all the elements in array then the array is
referred as one dimensional array.

Two dimensional array:


These are collection of homogeneous elements where the elements are ordered in a
number of rows and columns. To access an element in the two dimensional array we
require two subscripts.
int arr [ ][ ] = new int [5][5]
Operations on array:
Various operations that can be performed on an array are
a. Traversing.

Vasavi Degree College 30


Data Structures Unit-1 KHK

b. Sorting
c. Searching.
d. Insertion.
e. Deletion.
f. Merging.
a. Traversing:
i= L // start from lower bound
while(i<=U)
{
Process( a[i] )
i=i+1; // move to the next location
}
b. Sorting
This operation if performed on array , will sort it in a specified order(ascending /
descending)
i= U //initialized to upper bound
while(i>= L)
{
j = L;
While(j < i)
{
if(a[i]>a[j+i]) //comparing the order of elements
swap(a[j],a[j+]) // not in order , swap them
j=j+1;
}
I=i-1;
}
c. Searching:
This operation is applied to search an element of interest in an array.
a. I=L, found=0, location=0
b. While(i<=u && found==0)

Vasavi Degree College 31


Data Structures Unit-1 KHK

{
If(a[i]==KEY)
{
found=1;
location=i;
break;
}
else
i=i+1;
}
c. if(found==1)
print “ search is successful “
else
print “ search is not successful”

d. Insertion:
This operation is used to insert an element into an array provided that the array is
not full
1. i = U
2. while( i > LOCATION )
3. {
a[i]= a[i-1] // place the element in the next position
i=i-1;
}
4. A[LOCATION]=KEY; //put the element at the desired location
e. Deletion
This operation is used to delete a particular element from an array. The element
will be deleted by overwriting it with its subsequent element then is also to be
deleted.
1. i= searcharray(A, KEY)
if (i = = 0 )

Vasavi Degree College 32


Data Structures Unit-1 KHK

print “ KEY is not found “


EXIT;
2. while (i<U )
{
a[i]=a[i+1];
i=i+1;
}
3. a[U]=null;
4. U=U-1;
5. Stop;

Explain about Sparse Matrix?


In computer programming, a matrix can be defined with a 2-dimensional array. Any array
with 'm' columns and 'n' rows represents a mXn matrix. There may be a situation in
which a matrix contains more number of ZERO values than NON-ZERO values. Such
matrix is known as sparse matrix, i.e Sparse matrix is a matrix which contains very few
non-zero elements.
When a sparse matrix is represented with 2-dimensional array, we waste lot of space to
represent that matrix. For example, consider a matrix of size 100 X 100 containing only
10 non-zero elements. In this matrix, only 10 spaces are filled with non-zero values and
remaining spaces of matrix are filled with zero. That means, totally we allocate 100 X
100 X 4 = 40000 bytes of space to store this integer matrix. And to access these 10 non-
zero elements we have to make scanning for 10000 times.
Sparse Matrix Representations
A sparse matrix can be represented by using TWO representations, those are as follows...
 Triplet Representation
 Linked Representation
Triplet Representation
In this representation, we consider only non-zero values along with their row and column
index values. In this representation, the 0th row stores total rows, total columns and total

Vasavi Degree College 33


Data Structures Unit-1 KHK

non-zero values in the matrix. For example, consider a matrix of size 5 X 6 containing 6
number of non- zero values. This matrix can be represented as shown in the fig:

In above example matrix, there are only 6 non-zero elements ( those are 9, 8, 4, 2, 5 & 2)
and matrix size is 5 X 6. We represent this matrix as shown in the above image. Here the
first row in the right side table is filled with values 5, 6 & 6 which indicates that it is a
sparse matrix with 5 rows, 6 columns & 6 non-zero values. Second row is filled with 0, 4,
& 9 which indicates the value in the matrix at 0th row, 4th column is 9. In the same way
the remaining non-zero values also follows the similar pattern.
Linked Representation
In linked representation, we use linked list data structure to represent a sparse matrix. In
this linked list, we use two different nodes namely header node and element node.
Header node consists of three fields and element node consists of five fields as shown in
the image...

Consider the above same sparse matrix used in the Triplet representation. This sparse
matrix can be represented using linked representation as shown in the below image...

Vasavi Degree College 34


Data Structures Unit-1 KHK

In above representation, H0, H1,...,H5 indicates the header nodes which are used to
represent indexes. Remaining nodes are used to represent non-zero elements in the
matrix, except the very first node which is used to represent abstract information of the
sparse matrix (i.e., It is a matrix of 5 X 6 with 6 non-zero elements).
In this representation, in each row and column, the last node right field points to it's
respective header node.

Write a program to check whether the matrix is sparse matrix or not


import java.util.Scanner;
public class Sparsity_Matrix
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the dimensions of the matrix: ");
int m = sc.nextInt( );
int n = sc.nextInt( );

Vasavi Degree College 35


Data Structures Unit-1 KHK

int [ ][ ] mat = new int[m][n];


int zeros = 0;
System.out.println("Enter the elements of the matrix: ");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
mat[i][j] = sc.nextInt();
if(mat[i][j] == 0)
{
zeros++;
}
}
}
if(zeros > (m*n)/2)
System.out.println("The matrix is a sparse matrix");
else
System.out.println("The matrix is not a sparse matrix");
}
sc.close();
}}

Vasavi Degree College 36

You might also like