Data Structure and Algorithm

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

DSA Notes 21CS32

Module 01 : Introduction

Primitive vs non-primitive data structure


Data structure means organizing the data in the memory. The data can be organized in two ways
either linear or non-linear way.
There are two types of data structure available for the programming purpose:

• Primitive data structure

• Non-primitive data structure


Primitive data structure is a fundamental type of data structure that stores the data of only one type
whereas the non-primitive data structure is a type of data structure which is a user-defined that stores
the data of different types in a single entity.

In the above image, we can observe the classification of the data structure. The data structure is
classified into two types, i.e., primitive and non-primitive data structure. In the case of primitive data
structure, it contains fundamental data types such as integer, float, character, pointer, and these
fundamental data types can hold a single type of value. For example, integer variable can hold
integer type of value, float variable can hold floating type of value, character variable can hold
character type of value whereas the pointer variable can hold pointer type of value.
In the case of non-primitive data structure, it is categorized into two parts such as linear data
structure and non-linear data structure. Linear data structure is a sequential type of data structure, and

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

here sequential means that all the elements in the memory are stored in a sequential manner; for
example, element stored after the second element would be the third element, the element stored
after the third element would be the fourth element and so on. We have different linear data
structures holding the sequential values such asArray,Linked list,Stack,Queue.
Non-linear data structure is a kind of random type of data structure. The non-linear data structures
are Tree and Graph.
Primitive data structure Non-primitive data structure
Primitive data structure is a kind of data Non-primitive data structure is a type of data
structure that stores the data of only one structure that can store the data of more than one
type. type.

Examples of primitive data structure are Examples of non-primitive data structure are Array,
integer, character, float. Linked list, stack.

Primitive data structure will contain some Non-primitive data structure can consist of a NULL
value, i.e., it cannot be NULL. value.

The size depends on the type of the data In case of non-primitive data structure, size is not
structure. fixed.

It starts with a lowercase character. It starts with an uppercase character.

Primitive data structure can be used to call Non-primitive data structure cannot be used to call
the methods. the methods.

Primitive data structure


Primitive data structure is a data structure that can hold a single value in a specific location whereas
the non-linear data structure can hold multiple values either in a contiguous location or random
locations
The examples of primitive data structure are float, character, integer and pointer. The value to the
primitive data structure is provided by the programmer. The following are the four primitive data
structures:

•Integer:The integer data type contains the numeric values. It contains the whole numbers
that can be either negative or positive. When the range of integer data type is not large
enough then in that case, we can use long.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

•Float:The float is a data type that can hold decimal values. When the precision of decimal
value increases then the Double data type is used.

•Boolean:It is a data type that can hold either a True or a False value. It is mainly used for
checking the condition.

•Character:It is a data type that can hold a single character value both uppercase and
lowercase such as 'A' or 'a'.

Non-primitive data structure


The non-primitive data structure is a kind of data structure that can hold multiple values either in a
contiguous or random location. The non-primitive data types are defined by the programmer. The
non-primitive data structure is further classified into two categories, i.e., linear and non-linear data
structure.
In case of linear data structure, the data is stored in a sequence, i.e., one data after another data.
When we access the data from the linear data structure, we just need to start from one place and will
find other data in a sequence.
Array:An array is a data structure that can hold the elements of same type. It cannot contain the
elements of different types like integer with character. The commonly used operation in an array is
insertion, deletion, traversing, searching.
For example:
int a[6] = {1,2,3,4,5,6};
The above example is an array that contains the integer type elements stored in a contiguous manner.

•String:String is defined as an array of characters. The difference between the character array
and string is that the string data structure terminates with a 'NULL' character, and it is
denoted as a '\0'.
String data structure:

1. charname[100]="HellojavaTpoint";
Char Representation:

1. charname[100]={'H','e','l','l','o','','j','a','v','a','t','p','o','i','n','t'}
In the above example, the length of the string is 16 as it does not have any NULL character as the
last character to denote the termination.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

•Stack:Stack is a data structure that follows the principleLIFO(Last In First Out). All the
operations on the stack are performed from the top of the stack such as PUSH and POP
operation. The push operation is the process of inserting element into the stack while the pop
operation is the process of removing element from the stack. The stack data structure can be
implemented by using either array or linked list.

•Queue:Queue is a data structure that can be implemented by using array. The difference
between the stack and queue data structure is that the elements in the queue are inserted from
the rear end while the elements in the queue are removed from the front end.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

Operations on data structure


1)Traversing:Every data structure contains the set of data elements. Traversing the data structure
means visiting each element of the data structure in order to perform some specific operation like
searching or sorting.
Example:If we need to calculate the average of the marks obtained by a student in 6 different subject,
we need to traverse the complete array of marks and calculate the total sum, then we will devide that
sum by the number of subjects i.e. 6, in order to find the average.
2)Insertion:Insertion can be defined as the process of adding the elements to the data structure at any
location.
3)Deletion:The process of removing an element from the data structure is called Deletion. We can
delete an element from the data structure at any random location.
If we try to delete an element from an empty data structure then underflow occurs.
4)Searching:The process of finding the location of an element within the data structure is called
Searching. There are two algorithms to perform searching, Linear Search and Binary Search. We will
discuss each one of them later in this tutorial.
5)Sorting:The process of arranging the data structure in a specific order is known as Sorting. There are
many algorithms that can be used to perform sorting, for example, insertion sort, selection sort, bubble
sort, etc.
6)Merging:When two lists List A and List B of size M and N respectively, of similar type of elements,
clubbed or joined to produce the third list, List C of size (M+N), then this process is called merging

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

What Are Arrays in Data Structures?

An array is a linear data structure that collects elements of the same data type and stores them in
contiguous and adjacent memory locations. Arrays work on an index system starting from 0 to (n-1),
where n is the size of the array.
It is an array, but there is a reason that arrays came into the picture.

Why Do You Need an Array in Data Structures?

Let's suppose a class consists of ten students, and the class has to publish their results. If you had
declared all ten variables individually, it would be challenging to manipulate and maintain the data.
If more students were to join, it would become more difficult to declare all the variables and keep track
of it. To overcome this problem, arrays came into the picture.

What Are the Types of Arrays?


There are majorly two types of arrays, they are:

One-Dimensional Arrays:

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

You can imagine a 1d array as a row, where elements are stored one after another.

Multi-Dimensional Arrays:
These multi-dimensional arrays are again of two types. They are:

Two-Dimensional Arrays:

You can imagine it like a table where each cell contains elements.

Three-Dimensional Arrays:

You can imagine it like a cuboid made up of smaller cuboids where each cuboid can contain an
element.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

In this "arrays in data structures" tutorial, you will work around one-dimensional arrays

How Do You Declare an Array?

Arrays are typically defined with square brackets with the size of the arrays as its argument.
Here is the syntax for arrays:
1D Arrays: int arr[n];
2D Arrays: int arr[m][n];
3D Arrays: int arr[m][n][o];

How Do You Initialize an Array?


You can initialize an array in four different ways:

• Method 1:
int a[6] = {2, 3, 5, 7, 11, 13};

• Method 2:
int arr[]= {2, 3, 5, 7, 11};

• Method 3:
int n;
scanf(“%d”,&n);
int arr[n];
for(int i=0;i<5;i++)
{

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

scanf(“%d”,&arr[i]);
}

• Method 4:
int arr[5];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;

How Can You Access Elements of Arrays in Data Structures?

You can access elements with the help of the index at which you stored them. Let's discuss it with a
code:
#include<stdio.h>
int main()
{
int a[5] = {2, 3, 5, 7, 11};
printf(“%d\n”,a[0]); // we are accessing
printf(“%d\n”,a[1]);
printf(“%d\n”,a[2]);
printf(“%d\n”,a[3]);
printf(“%d”,a[4]);

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

return 0;
}

In this “Arrays in Data structures” tutorial, you have seen the basics of array implementation, now you
will perform operations on arrays.

What Operations Can You Perform on an Array?


•Traversal

•Insertion

•Deletion

•Searching

•Sorting

Traversing the Array:

Traversal in an array is a process of visiting each element once.


Code:
#include<stdio.h>

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

int main()
{
int a[5] = {2, 3, 5, 7, 11};
for(int i=0;i<5;i++)
{
//traversing ith element in the array
printf(“%d\n”,a[i]);
}
return 0;
}

Insertion:

Insertion in an array is the process of including one or more elements in an array.


Insertion of an element can be done:
•At the beginning

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

•At the end and

•At any given index of an array.

At the Beginning:
Code:
#include<stdio.h>
int main()
{
int array[10], n,i, item;
printf("Enter the size of array: ");
scanf("%d", &n);
printf("\nEnter Elements in array: ");
for(i=0;i<n;i++)
{
scanf("%d", &array[i]);
}
printf("\n enter the element at the beginning");
scanf("%d", &item);
n++;
for(i=n; i>1; i--)
{
array[i-1]=array[i-2];
}
array[0]=item;
printf("resultant array element");
for(i=0;i<n;i++)

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

{
printf("\n%d", array[i]);
}
getch();
return 0;
}

At the End:
Code:
#include<stdio.h>
#include<conio.h>
int main()
{
int array[10], i, values;
printf("Enter 5 Array Elements: ");
for(i=0; i<5; i++)
scanf("%d", &array[i]);
printf("\nEnter Element to Insert: ");

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

scanf("%d", &values);
array[i] = values;
printf("\nThe New Array is:\n");
for(i=0; i<6; i++)
printf("%d ", array[i]);
getch();
return 0;
}

At a Specific Position:
Code:
#include <stdio.h>
int main()
{
int array[100], pos, size, val;
printf("Enter size of the array:");
scanf("%d", &size);
printf("\nEnter %d elements\n", size);
for (int i = 0; i < size; i++)
scanf("%d", &array[i]);
printf("Enter the insertion location\n");

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

scanf("%d", &pos);
printf("Enter the value to insert\n");
scanf("%d", &val);
for (int i = size - 1; i >= pos - 1; i--)
array[i+1] = array[i];
array[pos-1] = val;
printf("Resultant array is\n");
for (int i = 0; i <= size; i++)
printf("%d\n", array[i]);
return 0;
}

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

Deletion:

Deletion of an element is the process of removing the desired element and re-organizing it.
You can also do deletion in different ways:
•At the beginning

•At the end

At the Beginning:
#include<stdio.h>
int main()
{
int n,array[10];
printf("enter the size of an array");
scanf("%d" ,&n);
printf("enter elements in an array");
for(int i=0;i<n;i++)
scanf("%d", &array[i]);
n--;

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

for(int i=0;i<n;i++)
array[i]=array[i+1];
printf("\nafter deletion ");
for(int i=0;i<n;i++)
printf("\n%d" , array[i]);
}

At the End:
#include<stdio.h>
int main()
{
int n,array[10];
printf("enter the size of an array");
scanf("%d" ,&n);
printf("enter elements in an array");
for(int i=0;i<n;i++)
scanf("%d", &array[i]);
printf("\nafter deletion array elements are");
for(int i=0;i<n-1;i++)

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

printf("\n%d" , array[i]);
}

Searching for an Element

The method of searching for a specific value in an array is known as searching.


There are two ways we can search in an array, they are:
•Linear search

•Binary search

Linear Search:
Code:
#include <stdio.h>
int linear(int a[], int n, int x)
{
for (int i = 0; i < n; i++)
if (a[i] == x)
return i;

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

return -1;
}
int main(void)
{
int a[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(a) / sizeof(a[0]);
// Function call
int result = linear(a, n, x);
if(result == -1)
{
printf("Element is not present in array");
}
else
{
printf("Element found at index: %d", result);
}
return 0;
}

Binary Search:
#include <stdio.h>
int binary(int a[], int lt, int rt, int k)
{
if (rt >= lt) {

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

int mid = lt + (rt - l) / 2;


// check If element is at the middle
if (a[mid] == k)
return mid;
//check if element is at the left side of mid
if (a[mid] > x)
return binary(a, lt, mid - 1, k);
// Else element is at the right side of mid
return binary(a, mid + 1, rt, k);
}
// if element not found
return -1;
}
int main(void)
{
int a[] = { 2, 3, 5, 7, 11 };
int n = sizeof(a) / sizeof(a[0]);
int k = 11;
int res = binary(arr, 0, n - 1, k);
if(res == -1)
{
printf("Element is not found")
}
else
{
printf("Element found at index %d",res);

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

}
return 0;
}

Sorting:

Sorting in an array is the process in which it sorts elements in a user-defined order.


Code:
#include <stdio.h>
void main()
{
int temp, size, array[100];
printf("Enter the size \n");
scanf("%d", &size);
printf("Enter the numbers \n");
for (int i = 0; i < size; ++i)
scanf("%d", &array[i]);

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

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


{
for (int j = i + 1; j < size; ++j)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
printf("sorted array:\n");
for (int i = 0; i < size; ++i)
printf("%d\n", array[i]);
}

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

What Are the Disadvantages of Arrays in Data Structures?


The number of elements in an array should be predefined
•An array is static. It cannot alter its size after declaration.

•Insertion and deletion operation in an array is quite tricky as the array stores elements in continuous
form.
•Allocating excess memory than required may lead to memory wastage.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

Stack Operations:

#include<stdio.h>
#include<stdlib.h>
#define Size 4

int Top=-1, inp_array[Size];


void Push();
void Pop();
void show();

int main()
{
int choice;

while(1)
{
printf("\nOperations performed by Stack");
printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");
printf("\n\nEnter the choice:");
scanf("%d",&choice);

switch(choice)
{
case 1: Push();
break;
case 2: Pop();
break;
case 3: show();
break;
case 4: exit(0);

default: printf("\nInvalid choice!!");


}
}
}

void Push()
{
int x;

if(Top==Size-1)

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

{
printf("\nOverflow!!");
}
else
{
printf("\nEnter element to be inserted to the stack:");
scanf("%d",&x);
Top=Top+1;
inp_array[Top]=x;
}
}

void Pop()
{
if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nPopped element: %d",inp_array[Top]);
Top=Top-1;
}
}

void show()
{

if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nElements present in the stack: \n");
for(int i=Top;i>=0;i--)
printf("%d\n",inp_array[i]);
}
}

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

What is a Stack?
A Stack is a linear data structure that follows the LIFO (Last-In-First-Out)principle. Stack has one
end, whereas the Queue has two ends (front and rear). It contains only one pointertop
pointerpointing to the topmost element of the stack. Whenever an element is added in the stack, it
is added on the top of the stack, and the element can be deleted only from the stack. In other words,
astack can be defined as a container in which insertion and deletion can be done from the one
end known as the top of the stack.

Some key points related to stack


•It is called as stack because it behaves like a real-world stack, piles of books, etc.

•A Stack is an abstract data type with a pre-defined capacity, which means that it can store
the elements of a limited size.
•It is a data structure that follows some order to insert and delete the elements, and that order
can be LIFO or FILO.

Working of Stack
Stack works on the LIFO pattern. As we can observe in the below figure there are five memory
blocks in the stack; therefore, the size of the stack is 5.
Suppose we want to store the elements in a stack and let's assume that stack is empty. We have
taken the stack of size 5 as shown below in which we are pushing the elements one by one until the
stack becomes full.

Since our stack is full as the size of the stack is 5. In the above cases, we can observe that it goes
from the top to the bottom when we were entering the new element in the stack. The stack gets
filled up from the bottom to the top.

When we perform the delete operation on the stack, there is only one way for entry and exit as the
other end is closed. It follows the LIFO pattern, which means that the value entered first will be

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

removed last. In the above case, the value 5 is entered first, so it will be removed only after the
deletion of all the other elements.

Standard Stack Operations


The following are some common operations implemented on the stack:
•push():When we insert an element in a stack then the operation is known as a push. If the
stack is full then the overflow condition occurs.
•pop():When we delete an element from the stack, the operation is known as a pop. If the
stack is empty means that no element exists in the stack, this state is known as an underflow
state.
•isEmpty():It determines whether the stack is empty or not.

•isFull():It determines whether the stack is full or not.'

•peek():It returns the element at the given position.

•count():It returns the total number of elements available in a stack.

•change():It changes the element at the given position.

•display():It prints all the elements available in the stack.

PUSH operation
The steps involved in the PUSH operation is given below:
•Before inserting an element in a stack, we check whether the stack is full.

•If we try to insert the element in a stack, and the stack is full, then theoverflowcondition
occurs.
•When we initialize a stack, we set the value of top as -1 to check that the stack is empty.

•When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e.,top=top+1,and the element will be placed at the new position of thetop.
•The elements will be inserted until we reach the maxsize of the stack.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

POP operation
The steps involved in the POP operation is given below:
•Before deleting the element from the stack, we check whether the stack is empty.

•If we try to delete the element from the empty stack, then theunderflowcondition occurs.

•If the stack is not empty, we first access the element which is pointed by thetop

•Once the pop operation is performed, the top is decremented by 1, i.e.,top=top-1.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

Applications of Stack
The following are the applications of the stack:
•Balancing of symbols:Stack is used for balancing a symbol. For example, we have the
following program:
1. int main()
2. {
3. cout<<"Hello";
4. cout<<"javaTpoint";
5. }
As we know, each program hasan openingandclosingbraces; when the opening braces come, we
push the braces in a stack, and when the closing braces appear, we pop the opening braces from the
stack. Therefore, the net value comes out to be zero. If any symbol is left in the stack, it means that
some syntax occurs in a program.
•String reversal:Stack is also used for reversing a string. For example, we want to reverse a
"javaTpoint" string, so we can achieve this with the help of a stack.
First, we push all the characters of the string in a stack until we reach the null character.
After pushing all the characters, we start taking out the character one by one until we reach
the bottom of the stack.
•UNDO/REDO:It can also be used for performing UNDO/REDO operations. For example,
we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text written in an
editor is abc. So, there are three states, a, ab, and abc, which are stored in a stack. There
would be two stacks in which one stack shows UNDO state, and the other shows REDO
state.
If we want to perform UNDO operation, and want to achieve 'ab' state, then we implement
pop operation.
•Recursion:The recursion means that the function is calling itself again. To maintain the
previous states, the compiler creates a system stack in which all the previous records of the
function are maintained.
•DFS(Depth First Search):This search is implemented on a Graph, and Graph uses the
stack data structure.
•Backtracking:Suppose we have to create a path to solve a maze problem. If we are moving
in a particular path, and we realize that we come on the wrong way. In order to come at the
beginning of the path to create a new path, we have to use the stack data structure.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura


DSA Notes 21CS32

•Expression conversion:Stack can also be used for expression conversion. This is one of
the most important applications of stack. The list of the expression conversion is given
below:
Infix to prefix
Infix to postfix
Prefix to infix
Prefix to postfix
Postfix to infix
•Memory management:The stack manages the memory. The memory is assigned in the
contiguous memory blocks. The memory is known as stack memory as all the variables are
assigned in a function call stack memory. The memory size assigned to the program is
known to the compiler. When the function is created, all its variables are assigned in the
stack memory. When the function completed its execution, all the variables assigned in the
stack are released.

Aslam.J.K Dept of CSE,Secab.I.E.T, Vijayaura

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy