You are on page 1of 63

Silver Oak College of

Engineering and Technology

SILVER OAK UNIVERSITY

BACHELOR OF ENGINEERING

Data Structures
(1010043216)
3rd SEMESTER

Laboratory Manual

COMPUTER ENGINEERING
Prepared by: Rushabh Vipulkumar Patel
Roll No: CS-A-047
Enrollment No: 200103072050
DEPARTMENT OF COMPUTER ENGINEERING

VISION
To be recognized for the quality education and research in the field of COMPUTER
ENGINEERING known for its accomplished graduates.

MISSION
1. Continually improve the standard of our graduates by engaging in innovative teaching learning
methods with high caliber motivated faculty members keeping in-line with the rapid
technological advancements.
2. Promote and support research activities over a wide range of academic interests among
students and staff for growth of individual knowledge and continuous learning.
3. Provide an education system that promotes innovation, creativity, entrepreneurial spirit,
leadership as well as freedom of thought with emphasis on professionalism and ethical behavior.

PROGRAM EDUCATIONAL OBJECTIVES (PEO):

PEO1: To provide fundamental knowledge of science and engineering for an IT professional


and to equip them with proficiency of mathematical foundations and algorithmic principles and
inculcate competent problem-solving ability.

PEO2: To implant ability in creativity & design of IT systems and transmit knowledge and skills
to analyze, design, test and implement various software applications.

PEO3: To exhibit leadership capability, triggering social and economical commitment and
inculcate community services.

PEO4: To inculcate professional-social ethics, teamwork in students and acquaint them with
requisite technical and managerial skills to attain a successful career.

6
PROGRAM OUTCOMES (POs):

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
7
clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

8
DATA STRUCTURES PRACTICAL BOOK

DEPARTMENT OF COMPUTER ENGINEERING

PREFACE

Before introducing data structures, we should understand that computers do store, retrieve, and
process a large amount of data. If the data is stored in well-organized way on storage media and
in computer's memory, then it can be accessed quickly for processing that further reduces the
latency and the user is provided fast response.

Data structure introduction refers to a scheme for organizing data, or in other words a data
structure is an arrangement of data in computer's memory in such a way that it could make the
data quickly available to the processor for required calculations. A data structure should be seen
as a logical concept that must address two fundamental concerns. First, how the data will be
stored, and second, what operations will be performed on it? As data structure is a scheme for
data organization so the functional definition of a data structure should be independent of its
implementation. The functional definition of a data structure is known as ADT (Abstract Data
Type) which is independent of implementation.

Lab Manual Revised by: Prof. Jigar Dalvadi, Prof. Digant Parmar, Prof. Rakesh Shah Silver
Oak College of Engineering and Technology

Lab Manual Revision No.:SOU_1010043216_LM_2021-22_1

9
TABLE OF CONTENT
Page No Sign Remarks
Sr.
Experiment Title
No
From To

Write a program to illustrate the concept of


1
call by value, call by reference.

Write a program to illustrate the concept of


2
Pointers and Dynamic Memory Allocation.
Implement a program for Stack that performs
following operations using array.
3
(a) PUSH (b) POP (c) CHANGE (d)
DISPLAY
Write a program to implement Queue using
4 arrays that performs following operations
(a) INSERT (b) DELETE (c) DISPLAY
Implement a program to convert infix
5
notation to postfix notation using stack.
Write a menu driven program to implement
following operations on the singly linked list.
Insert a node at the front of the linked
6 list.
Insert a node at the end of the linked list.
Delete a first node of the linked list.
Delete a node after specified Position.
Write a program to implement stack using
7
linked list.

Write a program which create binary search


8
tree

9 Write a program to implement binary search

Write the program for following sorting


10 algorithms QuickSort
MergeSort

10
PRACTICAL – 1

AIM: Write a program to illustrate the concept of call by value, call by reference.

There are two ways to pass arguments/parameters to function calls -- call by value and call by
reference. The major difference between call by value and call by reference is that in call by
value a copy of actu1al arguments is passed to respective formal arguments. While, in call by
reference the location (address) of actual arguments is passed to formal arguments, hence any
change made to formal arguments will also reflect in actualarguments.

In C, all function arguments are passed "by value" because C does not support references like C+
+ and Java do. In C, the calling and called functions do not share any memory -- they have their
own copy and the called function cannot directly alter a variable in the calling function; it can
only alter its private, temporary copy.

The call by value scheme is an asset, however, not a liability. It usually leads to more compact
programs with fewer extraneous variables, because parameters can be treated as conveniently
initialized local variables in the called routine. Yet, there are some cases where we need call by
reference:

The called function communicates to the calling function only through return statement and
return statement can only send only one value back to the calling function. If there are more than
one value we want to alter, call by reference is required

If the size of data is large, copying actual arguments to formal arguments could be a time
consuming operation and occupies more memory.

The call by value does not address above cases, hence we need call by reference. To achieve call
by reference functionality in C language the calling function provides the address of the variable
to be set (technically a pointer to the variable), and the called function declares the parameter to
be a pointer and access the variable indirectly through it. Since the address of the argument is
passed to the function, code within the called function can change the value of the actual
arguments.

While studying call by value and call by reference in C it is important to note that the story is
different for arrays. When the name of an array is used as an argument, the value passed to the
function is the location or address of the beginning of the array --there is no copying of array
elements. By subscripting this value, the function can access and alter any element of the actual
array.

Difference between call by value and call by reference

CALL BY VALUE CALL BY REFERENCE


In call by value, a copy of actual arguments is In call by reference, the location (address) of
passed to formal arguments of the called actual arguments is passed to formal
function and any change made to the formal arguments of the called function. This means
arguments in the called function have no effect by accessing the addresses of actual
on the values of actual arguments in the calling arguments we can alter them within from the
function. called function.
In call by reference, alteration to actual
arguments is possible within from called
In call by value, actual arguments will remain
function; therefore the code must handle
safe, they cannot be modified accidentally.
arguments carefully else you get unexpected
results.

Practical Code:

Call By Value:

// call by value

#include<stdio.h>
#include<conio.h>

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
int a = 10, b = 20;

// Pass by Values
swapx(a, b);

printf("a=%d b=%d\n", a, b);

return 0;
}

// Swap functions that swaps


// two values
void swapx(int x, int y)
{
int t;

t = x;
x = y;
y = t;

printf("x=%d y=%d\n", x, y);


}

Call By Reference:

// Call by Reference

#include<stdio.h>
#include<conio.h>

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b);

printf("a=%d b=%d\n", a, b);


return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y)
{
int t;

t = *x;
*x = *y;
*y = t;

printf("x=%d y=%d\n", *x, *y);


}

Output:

Call By Value:
PRACTICAL-2

AIM:-Write a program to illustrate the concept of Pointers and Dynamic Memory Allocation.

Dynamic memory management refers to manual memory management. This allows you to obtain
more memory when required and release it when not necessary.

Although C inherently does not have any technique to allocate memory dynamically, there are 4
library function defined under <stdlib.h> for dynamic memory allocation.

Functio Use of Function


n
malloc( Allocates requested size of bytes and returns a pointer first byte of allocated space
)
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
free() deallocate the previously allocated space
realloc( Change the size of previously allocated space
)

C malloc()

The name malloc stands for "memory allocation".

The function malloc() reserves a block of memory of specified size and return a pointer of type void
which can be casted into pointer of any form.

Syntax of malloc()

ptr = (cast-type*) malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with
size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.

ptr = (int*) malloc(100 * sizeof(int));


This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and
the pointer points to the address of first byte of memory.

C calloc()

The name calloc stands for "contiguous allocation".

The only difference between malloc() and calloc() is that, malloc() allocates single block of memory
whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.

Syntax of calloc()

ptr = (cast-type*)calloc(n, element-size);

This statement will allocate contiguous space in memory for an array of n elements. For example:

Ptr = (float*)calloc(25,sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of size of
float, i.e, 4bytes.

C free()

Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own.
You must explicitly use free() to release the space.

syntax of free() free(ptr);

This statement frees the space allocated in the memory pointed by ptr.
Practical Code:
malloc() function:
#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

return 0;
}

calloc() function:
#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()


ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

return 0;
}
Output:
Malloc() function:

Calloc() function:
References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.htm
3. https://www.coursera.org/learn/data-structures
4. https://www.studytonight.com/data-structures/introduction-to-data-structures
5. www.srmuniv.ac.in/sites/default/.../It0501Data%20Structures&Algorithms%20Lab.pdf
6. https://www.wctmgurgaon.com/wctm/dsa%20lab-it-labmanual.pdf
PRACTICAL-3
AIM: Implement a program for Stack that performs following operations using array.
(a)PUSH (b) POP (c) CHANGE (d) DISPLAY

A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of
plates,etc.

A real-world stack allows operations at one end only. For example, we can place or remove a
card or plate from the top of the stack only. Likewise, Stack ADT allows all data operations at
one end only. At any given time, we can only access the top element of a stack.

This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element
which is placed (inserted or added) last, is accessed first. In stack terminology, insertion
operation is called PUSH operation and removal operation is called POP operation.

A stack can be implemented by means of Array, Structure, Pointer, and Linked List. Stack can
either be a fixed size one or it may have a sense of dynamic resizing. Here, we are going to
implement stack using arrays, which makes it a fixed size stack implementation.

Basic Operations

Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from
these basic stuffs, a stack is used for the following two primary operations −

push() − Pushing (storing) an element on the stack.

pop() − Removing (accessing) an element from the stack.

Peep() - Returning particular value from stack

change() - Change particular value in stack


Practical Code:
#include<stdio.h>
Int stack[100],choice,n,top,x,I;
Void push(void);
Void pop(void);
Void display(void);
Int main()
{
//clrscr();
Top=-1;
Scanf(“%d”,&n);
Printf(“\n\t STACK OPERATIONS USING ARRAY”);
Printf(“\n\t--------------”);
Printf(“\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT”);
Do
{
Printf(“\n Enter the Choice:”);
Scanf(“%d”,&choice);
Switch(choice)
{
Case 1:
{
Push();
break;
}
Case 2:
{
Pop();
Break;
}
Case 3:
{
Display();
Break;
}
Case 4:
{
Printf(“\n\t EXIT POINT”);
Break;
}
Defult;
{
Printf(“\n\t Please Enter a Valid Choice(1/2/3/4)”);
}
}
}
While(choice!=4);
Return0
Output:
References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.htm
3. https://www.coursera.org/learn/data-structures
4. https://www.studytonight.com/data-structures/introduction-to-data-structures
5. www.srmuniv.ac.in/sites/default/.../It0501Data%20Structures&Algorithms%20Lab.pdf
6. https://www.wctmgurgaon.com/wctm/dsa%20lab-it-labmanual.pdf
PRACTICAL-4

AIM: Write a program to implement Queue using arrays that performs following
operations (a) INSERT (b) DELETE (c) DISPLAY

Like Stack, Queue is a linear structure which follows a particular order in which the operations
are performed. The order is First in First out (FIFO). A good example of queue is any queue
of consumers for a resource where the consumer that came first is served first.
The difference between stacks and queues is in removing. In a stack we remove the item the
most recently added; in a queue, we remove the item the least recently added.
Operations on Queue:
Mainly the following four basic operations are performed on queue:
Enqueue / Insert: Adds an item to the queue. If the queue is full, then it is said to be an
Overflow condition.
Dequeue / Delete: Removes an item from the queue. The items are popped in the same order in
which they are pushed. If the queue is empty, then it is said to be an Underflow condition.
Front : Get the front item from queue.
Rear : Get the last item from queue.
Queue is used when things don’t have to be processed immediately, but have to be processed in
First In First Out order like Breadth First Search. This property of Queue makes it also useful
in following kind of scenarios.
1) When a resource is shared among multiple consumers. Examples include CPU scheduling,
Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate assent)
between two processes. Examples include IO Buffers, pipes, file IO,etc.

Practical Code:
Output:

References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.htm
3. https://www.coursera.org/learn/data-structures
4. https://www.studytonight.com/data-structures/introduction-to-data-structures
5. www.srmuniv.ac.in/sites/default/.../It0501Data%20Structures&Algorithms%20Lab.pdf
6. https://www.wctmgurgaon.com/wctm/dsa%20lab-it-labmanual.pdf
PRACTICAL-5
AIM: Implement a program to convert infix notation to postfix notation using stack.

Any expression can be represented using three types of expressions (Infix, Postfix and Prefix).
We can also convert one type of expression to another type of expression like Infix to Postfix,
Infix to Prefix, Postfix to Prefix and vice versa. To convert any Infix expression into Postfix or
Prefix expression we can use the following procedure…
Find all the operators in the given Infix Expression.
Find the order of operators evaluated according to their Operator precedence.
Convert each operator into required type of expression (Postfix or Prefix) in the same order.
To convert Infix Expression into Postfix Expression using a stack data structure, We can use the
following steps...
Read all the symbols one by one from left to right in the given Infix Expression. If the reading
symbol is operand, then directly print it to the result (Output).
If the reading symbol is left parenthesis '(', then Push it on to the Stack.
If the reading symbol is right parenthesis ')', then Pop all the contents of stack until respective left
parenthesis is poped and print each poped symbol to the result.
If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However, first
pop the operators which are already on the stack that have higher or equal precedence than
current operator and print them to the result.

Practical Code:
Output:

References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.htm
3. https://www.coursera.org/learn/data-structures
4. https://www.studytonight.com/data-structures/introduction-to-data-structures
5. www.srmuniv.ac.in/sites/default/.../It0501Data%20Structures&Algorithms%20Lab.pdf
6. https://www.wctmgurgaon.com/wctm/dsa%20lab-it-labmanual.pdf
PRACTICAL-6

AIM: Write a menu driven program to implement following operations on the singly linked
list.
Insert a node at the front of the linked list.
Insert a node at the end of the linked list.
Delete a first node of the linked list.
Delete a node after specified position.

Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not
stored at contiguous location; the elements are linked using pointers.
Why Linked List?
Arrays can be used to store linear data of similar types, but arrays have following limitations.
1) The size of the arrays is fixed: So we must know the upper limit on the number of elements
in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the
usage.
2) Inserting a new element in an array of elements is expensive, because room has to be created
for the new elements and to create room existing elements have to beshifted.

Operations on Linked Lists:

Appending a node to a Linked List


Prepending a node to a linked list
Inserting a node in order to a linked list
Deleting a node from a linked list
Practical Code:
Output:

References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.htm
3. https://www.coursera.org/learn/data-structures
4. https://www.studytonight.com/data-structures/introduction-to-data-structures
5. www.srmuniv.ac.in/sites/default/.../It0501Data%20Structures&Algorithms%20Lab.pdf
6. https://www.wctmgurgaon.com/wctm/dsa%20lab-it-labmanual.pdf
PRACTICAL-7
AIM: Write a program to implement stack using linked list.

The major problem with the stack implemented using array is, it works only for fixed number of
data values. That means the amount of data must be specified at the beginning of the
implementation itself. Stack implemented using array is not suitable, when we don't know the
size of data which we are going to use. A stack data structure can be implemented by using
linked list data structure. The stack implemented using linked list can work for unlimited number
of values. That means, stack implemented using linked list works for variable size of data. So,
there is no need to fix the size at the beginning of the implementation. The Stack implemented
using linked list can organize as many data values as we want.

In linked list implementation of a stack, every new element is inserted as 'top' element. That
means every newly inserted element is pointed by 'top'. Whenever we want to remove an element
from the stack, simply remove the node which is pointed by 'top' by moving 'top' to its next node
in the list. The next field of the first element must be always NULL.
Operations:
To implement stack using linked list, we need to set the following things before implementing
actual operations.
Step 1: Include all the header files which are used in the program. And declare all the user
defined functions.
Step 2: Define a 'Node' structure with two members data and next.
Step 3: Define a Node pointer 'top' and set it to NULL.
Step 4: Implement the main method by displaying Menu with list of operations and make
suitable function calls in the main method.
push(value) - Inserting an element into the Stack
We can use the following steps to insert a new node into the stack...
Step 1: Create a newNode with given value.
Step 2: Check whether stack is Empty (top == NULL)
Step 3: If it is Empty, then set newNode → next = NULL.
Step 4: If it is Not Empty, then set newNode → next =
top. Step 5: Finally, set top = newNode.
pop() - Deleting an Element from a Stack

We can use the following steps to delete a node from the


stack... Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate
the function
Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4: Then set 'top = top → next'.
Step 7: Finally, delete 'temp' (free(temp)).
display() - Displaying stack of elements
We can use the following steps to display the elements (nodes) of a
stack... Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until temp
reaches to the first node in the stack (temp → next != NULL).
Step 4: Finally! Display 'temp → data ---> NULL'.

Practical Code:
Output:

References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.htm
3. https://www.coursera.org/learn/data-structures
4. https://www.studytonight.com/data-structures/introduction-to-data-structures
5. www.srmuniv.ac.in/sites/default/.../It0501Data%20Structures&Algorithms%20Lab.pdf
6. https://www.wctmgurgaon.com/wctm/dsa%20lab-it-labmanual.pdf
PRACTICAL-8
AIM: Write a program which create binary search tree

Binary Search Tree is a node-based binary tree data structure which has the following properties:

● The left subtree of a node contains only nodes with keys lesser than the node’s key.
● The right subtree of a node contains only nodes with keys greater than the node’s key.
● The left and right subtree each must also be a binary search tree.

Practical Code:
Output:

References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.ht0m
3. https://www.coursera.org/learn/data-structures
PRACTICAL-9
AIM: Write a program to implement binary search

Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check
until the value is found or the interval is empty.

Example : 

● Compare x with the middle element.


● If x matches with the middle element, we return the mid index.
● Else If x is greater than the mid element, then x can only lie in the right half subarray after the
mid element. So we recur for the right half.
● Else (x is smaller) recur for the left half.
Practical Code:
Output:

References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.ht0m
3. https://www.coursera.org/learn/data-structures
PRACTICAL-10

AIM: Write the program for following sorting algorithms.


Merge Sort
Quick Sort

1) Merge Sort

In merge sort, we break the given array midway, for example if the original array had 6 elements,
then merge sort will break it down into two sub arrays with 3 elements each.

But breaking the orignal array into 2 smaller sub arrays is not helping us in sorting the array.

So we will break these sub arrays into even smaller sub arrays, until we have multiple sub arrays
with single element in them. Now, the idea here is that an array with a single element is already
sorted, so once we break the original array into sub arrays which has only a single element, we
have successfully broken down our problem into base problems.

And then we have to merge all these sorted sub arrays, step by step to form one single sorted
array.

Let's consider an array with values {14, 7, 3, 12, 9, 11, 6, 12}

Below, we have a pictorial representation of how merge sort will sort the given array.
Practical Code:
Output:

2) Quick Sort

Following are the steps involved in quick sort algorithm:


After selecting an element as pivot, which is the last index of the array in our case, we dividethe
array for the firsttime.
In quick sort, we call this partitioning. It is not simple breaking down of array into 2 subarrays,
but in case of partitioning, the array elements are so positioned that all the elements smaller than
the pivot will be on the left side of the pivot and all the elements greater than the pivot will be on
the right side of it.
And the pivot element will be at its final sorted position.
The elements to the left and right, may not be sorted.
Then we pick subarrays, elements on the left of pivot and elements on the right of pivot, and we
perform partitioning on them by choosing a pivot in the subarrays.
Let's consider an array with values {9, 7, 5, 11, 12, 2, 14, 3, 10,6}

Below, we have a pictorial representation of how quick sort will sort the given array.

In step 1, we select the last element as the pivot, which is 6 in this case, and call for partitioning,
hence re-arranging the array in such a way that 6 will be placed in its final position and to its left
will be all the elements less than it and to its right, we will have all the elements greater than it.

Then we pick the subarray on the left and the sub array on the right and select a pivot for them,
in the above diagram, we chose 3 as pivot for the left sub array and 11 as pivot for the right
subarray.
And we again call for partitioning.
Practical Code:
Output:
References:

1. https://www.geeksforgeeks.org/data-structures/
2. https://www.tutorialspoint.com/data_structures_algorithms/data_structures_basics.htm
3. https://www.coursera.org/learn/data-structures
4. https://www.studytonight.com/data-structures/introduction-to-data-structures
5. www.srmuniv.ac.in/sites/default/.../It0501Data%20Structures&Algorithms%20Lab.pdf
6. https://www.wctmgurgaon.com/wctm/dsa%20lab-it-labmanual.pdf

You might also like