Data Structure and Algorithm
Data Structure and Algorithm
Data Structure and Algorithm
Module 01 : Introduction
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
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.
Primitive data structure can be used to call Non-primitive data structure cannot be used to call
the methods. the methods.
•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.
•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'.
•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.
•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.
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.
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.
One-Dimensional Arrays:
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.
In this "arrays in data structures" tutorial, you will work around one-dimensional arrays
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];
• 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++)
{
scanf(“%d”,&arr[i]);
}
• Method 4:
int arr[5];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
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]);
return 0;
}
In this “Arrays in Data structures” tutorial, you have seen the basics of array implementation, now you
will perform operations on arrays.
•Insertion
•Deletion
•Searching
•Sorting
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:
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++)
{
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: ");
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");
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;
}
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 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--;
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++)
printf("\n%d" , array[i]);
}
•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;
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) {
}
return 0;
}
Sorting:
•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.
Stack Operations:
#include<stdio.h>
#include<stdlib.h>
#define Size 4
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);
void Push()
{
int x;
if(Top==Size-1)
{
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]);
}
}
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.
•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
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.
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.
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
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.
•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.