0% found this document useful (0 votes)
35 views33 pages

Data Structure - Solution

The document contains questions and answers related to the Basic Data Structure and Algorithm exam. It includes definitions of Big-O notation, sparse matrices, stack operations, array representation of stacks, binary trees, complexity of searching algorithms, graphs and multigraphs, minimum spanning trees, binary search, B+ trees. It also discusses string operations, priority queues, complete binary trees, and breadth-first search. The questions cover key concepts in data structures and algorithms.

Uploaded by

wrdmania15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
35 views33 pages

Data Structure - Solution

The document contains questions and answers related to the Basic Data Structure and Algorithm exam. It includes definitions of Big-O notation, sparse matrices, stack operations, array representation of stacks, binary trees, complexity of searching algorithms, graphs and multigraphs, minimum spanning trees, binary search, B+ trees. It also discusses string operations, priority queues, complete binary trees, and breadth-first search. The questions cover key concepts in data structures and algorithms.

Uploaded by

wrdmania15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 33

Printed Page: 1 of 1

Subject Code: KOE035

B TECH
(SEM-III) THEORY EXAMINATION 2020-21
BASIC DATA STRUCTURE AND
ALGORITHM
Time: 3 Hours Total Marks: 100
Note: 1. Attempt all Sections. If require any missing data; then choose suitably.
SECTION A

Qa: Explain Big-oh notation.

Ans:“Big O notation is a mathematical notation that describes the limiting behavior of a function
when the argument tends towards a particular value or infinity. Definition: A theoretical
measure of the execution of an algorithm, usually the time or memory needed, given the problem
size n, which is usually the number of items. Informally, saying some equation f(n) = O(g(n))
means it is less than some constant multiple of g(n). The notation is read, "f of n is big oh of g of
n".

Formal Definition: f(n) = O(g(n)) means there are positive constants c and k, such that 0 ≤ f(n)
≤ cg(n) for all n ≥ k. The values of c and k must be fixed for the function f and must not depend
on n.

Qb: What do you understand by sparse matrix?


Ans: Sparse matrices are those matrices that have the majority of their elements equal to
zero. In other words, the sparse matrix can be defined as the matrix that has a greater number
of zero elements than the non-zero elements.
Qc: Discuss stack operations
1. Push(): the process of adding a new element to the top of the stack is called PUSH
operation.
2. POP(): the process of deleting an element from the top of the stack is called pop
operation.
3. peek() − get the top data element of the stack, without removing it.

Qd: What is Array representation of stacks?


Ans: A stack can be implemented using array as follows...
Before implementing actual operations, first follow the below steps to create an empty stack.
Step 1 - Include all the header files which are used in the program and define a constant
'SIZE' with specific value.
Step 2 - Declare all the functions used in stack implementation.
Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5 - In main method, display menu with list of operations and make suitable function
calls to perform operation selected by the user on the stack.

Qe: Discuss Binary Tree.


Ans: A binary tree, is a tree in which no node can have more than two children.
• Consider a binary tree T, here ‘A’ is the root node of the binary tree T.
• ‘B’ is the left child of ‘A’ and ‘C’ is the right child of ‘A’
• i.e A is a father of B and C.
• The node B and C are called siblings.
Nodes D,H,I,F,J are leaf node

Qf: What do understand by Complexity of searching algorithm?


Ans: Searching Algorithms are designed to check for an element or retrieve an element from any
data structure where it is stored. Based on the type of search operation, these algorithms are
generally classified into two categories:
1. Sequential Search: In this, the list or array is traversed sequentially and every element is
checked. For example: Linear Search.
2. Interval Search: These algorithms are specifically designed for searching in sorted data-
structures. These type of searching algorithms are much more efficient than Linear Search as
they repeatedly target the center of the search structure and divide the search space in half.
For Example: Binary Search.

Qg: Explain Graphs & Multigraph.


Ans: Graph is a non-linear data structure. It contains a set of points known as nodes (or vertices)
and a set of links known as edges (or Arcs). Here edges are used to connect the vertices.
A graph whose edges are unordered pairs of vertices, and the same pair of vertices can be
connected by multiple edges. Formal Definition: Same as graph, but E is a bag of edges, not a
set.

Qh: What is Minimum Cost spanning tree?


Ans: A Minimum Spanning Tree (MST) works on graphs with directed and weighted (non-
negative costs) edges. Consider a graph G with n vertices. The spanning tree is a subgraph of
graph G with all its n vertices connected to each other using n-1 edges.

Qi: Discuss binary Search.


Ans: 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.

QJ: Explain B+ Tree.


Ans: B+ Tree is an extension of B Tree which allows efficient insertion, deletion and search
operations. In B Tree, Keys and records both can be stored in the internal as well as leaf nodes.
Whereas, in B+ tree, records (data) can only be stored on the leaf nodes while internal nodes can
only store the key values.

SECTION B
Attempt any three of the following:
Qa: What is meant by string operation? Discuss with the help of any example.
Ans: Strings are defined as an array of characters. The difference between a character array and a
string is the string is terminated with a special character ‘\0’.
Declaring a string is as simple as declaring a one dimensional array. Below is the basic syntax for
declaring a string in C programming language.
char str_name[size];

Operation Description
Concatenati
The Addition operator, “+”, can be used to concatenate strings together.
on
Formatting The STRING function is used to format data into a string. The READS procedure
Data can be used to read values from a string into IDL variables.
The ToLower() method returns a copy of the string converted to lowercase.
Case Similarly, the ToUpper() method returns a copy converted to uppercase.
Folding The CapWords() method returns a copy where the first letter of each word is
capitalized. See also the STRLOWCASE and STRUPCASE functions.
White Space The Compress() and Trim() methods can be used to eliminate unwanted white
Removal space. See also the STRCOMPRESS and STRTRIM functions.
Length The Strlen() method (or STRLEN function) returns the length of the string.
See
the CharAt(), Extract(), IndexOf(), Insert(), LastIndexOf(), Remove(), Replace(),
Substrings
Reverse(), and Substring() methods. See also the STRPOS, STRPUT,
and STRMID routines.
Splitting and The Split() method is used to break strings apart, and the Join() method can be
Joining used to join them. See also the STRSPLIT and STRJOIN functions.
The "EQ" operator can be used to directly compare two strings.
Comparing The Contains(), EndsWith(), Matches(), and StartsWith() methods can be used to
Strings compare portions of strings. See also the STRCMP, STRMATCH,
and STREGEX functions.

Qb: Explain Priority Queue and Define Big-Oh notation and find the complexity of the
following recursive function T(n) = 4T(n/2)+nlog n
Ans:
Priority Queue: A priority queue is a special type of queue in which each element is associated
with a priority value. And, elements are served on the basis of their priority. That is, higher
priority elements are served first.
However, if elements with the same priority occur, they are served according to their order in the
queue.

Assigning Priority Value


Generally, the value of the element itself is considered for assigning the priority. For example,
The element with the highest value is considered the highest priority element. However, in other
cases, we can assume the element with the lowest value as the highest priority element.

We can also set priorities according to our needs.

O Notation:

For function g(n), we define O(g(n)), big-O of n, as the set:

F(n)=O(g(n)) :
 positive constants c and n0, such that n  n0,

we have 0  f(n)  cg(n) }

T(n)=4T(n/2)+n∗log(n)T(n)=4T(n/2)+n∗log(n)
T(n/2)=4T(n/4)+(n/2)∗(log(n)−1)T(n/2)=4T(n/4)+(n/2)∗(log(n)−1)
Plugging in 1st Eqn. :

T(n)=(42)T(n/4)+(4∗(n/2)(log(n)−1))+n∗log(n)T(n)=(42)T(n/4)+(4∗(n/2)(log(n)−1))+n∗log(n)
Also,T(n/4)=4T(n/8)+(n/4)∗(log(n)−2)Also,T(n/4)=4T(n/8)+(n/4)∗(log(n)−2)
Plugging again…

T(n)=(43)T(n/8)+(4∗(n/4)(log(n)−2))+(4∗(n/2)(log(n)−1))+n∗log(n)

So following this pattern…

T(n)=(4k)T(n/2k)+4∗(∑2k((n/2r−1)(log(n)−(r−1)))+n∗log(n)T(n)=(4k)T(n/2k)+4∗(∑2k((n/2r−1)(log(n)−(r−1)))+n∗log(
n)
k
Now , set n=2 .
Qc: Discuss Complete Binary Trees. Draw a binary tree for following data:

{15 22 12 1 8 7 17 25 23 6 9 2}

Ans:

• A complete binary tree is a binary tree in which every level, except possibly the last, is
completely

filled, and all nodes are as far left as possible.

• In complete binary tree all the nodes must have exactly two children and at every level of
complete binary tree there must be 2 level number of nodes.
• For example at level 2 there must be 2^2 = 4 nodes and at level 3 there must be 2^3 = 8
nodes.
• A complete binary tree of depth d is called strictly binary tree if all of whose leaves are at
level d.
• A complete binary tree has 2d nodes at every depth d and 2d -1

non leaf nodes

• A binary tree in which every internal node has exactly two

children and all leaf nodes are at same level is called

Complete Binary Tree.

• Complete binary tree is also called as Perfect Binary Tree


Qd: Discuss the Breadth First Search with the help of any example.

Ans: Breadth-first search (BFS) is an algorithm that is used to graph data or searching tree or
traversing structures. The full form of BFS is the Breadth-first search.

The algorithm efficiently visits and marks all the key nodes in a graph in an accurate breadthwise
fashion. This algorithm selects a single node (initial or source point) in a graph and then visits all
the nodes adjacent to the selected node. Remember, BFS accesses these nodes one by one.

Once the algorithm visits and marks the starting node, then it moves towards the nearest
unvisited nodes and analyses them. Once visited, all nodes are marked. These iterations continue
until all the nodes of the graph have been successfully visited and marked.

Graph traversal requires the algorithm to visit, check, and/or update every single un-visited node
in a tree-like structure. Graph traversals are categorized by the order in which they visit the
nodes on the graph.

BFS algorithm starts the operation from the first or starting node in a graph and traverses it
thoroughly. Once it successfully traverses the initial node, then the next non-traversed vertex in
the graph is visited and marked.
Hence, you can say that all the nodes adjacent to the current vertex are visited and traversed in
the first iteration. A simple queue methodology is utilized to implement the working of a BFS
algorithm, and it consists of the following steps:

Step 1)

Each vertex or node in the graph is known. For instance, you can mark the node as V.

Step 2)

In case the vertex V is not accessed then add the vertex V into the BFS Queue
Step 3)

Start the BFS search, and after completion, Mark vertex V as visited.

Step 4)

The BFS queue is still not empty, hence remove the vertex V of the graph from the queue.

Step 5)
Retrieve all the remaining vertices on the graph that are adjacent to the vertex V

Step 6)

For each adjacent vertex let's say V1, in case it is not visited yet then add V1 to the BFS queue

Step 7)
BFS will visit V1 and mark it as visited and delete it from the queue.

Example BFS Algorithm

Step 1)
You have a graph of seven numbers ranging from 0 – 6.

Step 2)
0 or zero has been marked as a root node.

Step 3)

0 is visited, marked, and inserted into the queue data structure.

Step 4)
Remaining 0 adjacent and unvisited nodes are visited, marked, and inserted into the queue.

Step 5)
Traversing iterations are repeated until all nodes are visited.

Rules of BFS Algorithm

Here, are important rules for using BFS algorithm:

 A queue (FIFO-First in First Out) data structure is used by BFS.


 You mark any node in the graph as root and start traversing the data from it.
 BFS traverses all the nodes in the graph and keeps dropping them as completed.
 BFS visits an adjacent unvisited node, marks it as done, and inserts it into a queue.
 Removes the previous vertex from the queue in case no adjacent vertex is found.
 BFS algorithm iterates until all the vertices in the graph are successfully traversed and
marked as completed.
 There are no loops caused by BFS during the traversing of data from any node.

Qe: Explain quick sort. Draw a tree of the following with the help of Quick sort:

{52,37,63,14,17,8,6,25}

Quick Sort is one of the different Sorting Technique which is based on the concept of Divide
and Conquer, just like merge sort. But in quick sort all the heavy lifting(major work) is done
while dividing the array into subarrays, while in case of merge sort, all the real work happens
during merging the subarrays. In case of quick sort, the combine step does absolutely nothing.

It is also called partition-exchange sort. This algorithm divides the list into three main parts:

1. Elements less than the Pivot element


2. Pivot element(Central element)
3. Elements greater than the pivot element
Pivot element can be any element from the array, it can be the first element, the last element or
any random element. In this tutorial, we will take the rightmost element or the last element
as pivot.

For example: In the array {52, 37, 63, 14, 17, 8, 6, 25}, we take 25 as pivot. So after the first
pass, the list will be changed like this.

{6 8 17 14 25 63 37 52}

Hence after the first pass, pivot will be set at its position, with all the elements smaller to it on its
left and all the elements larger than to its right. Now 6 8 17 14 and 63 37 52 are considered as
two separate sunarrays, and same recursive logic will be applied on them, and we will keep
doing this until the complete array is sorted.

SECTION C
Q3 a: What do you understand by complexity of an algorithm? Discuss at least 4 types of
string operations in details.
Ans: Space required to complete the task of that algorithm (Space Complexity).
Time required to complete the task of that algorithm (Time Complexity)
Space Complexity:
When we design an algorithm to solve a problem, it needs some computer memory to complete
its execution. For any algorithm, memory is required for the following purposes...
1. To store program instructions.
2. To store constant values.
3. To store variable values.
4. And for few other things like function calls, jumping statements etc,.
Total amount of computer memory required by an algorithm to complete its execution is
called as space complexity of that algorithm

Time Complexity:
• Every algorithm requires some amount of computer time to execute its instruction to
perform the task. This computer time required is called time complexity.
The time complexity of an algorithm can be defined as follows...
The time complexity of an algorithm is the total amount of time required by an algorithm
to complete its execution.

Operation Description
Concatenati
The Addition operator, “+”, can be used to concatenate strings together.
on
Formatting The STRING function is used to format data into a string. The READS procedure
Data can be used to read values from a string into IDL variables.
The ToLower() method returns a copy of the string converted to lowercase.
Case Similarly, the ToUpper() method returns a copy converted to uppercase.
Folding The CapWords() method returns a copy where the first letter of each word is
capitalized. See also the STRLOWCASE and STRUPCASE functions.
White Space The Compress() and Trim() methods can be used to eliminate unwanted white
Removal space. See also the STRCOMPRESS and STRTRIM functions.
Length The Strlen() method (or STRLEN function) returns the length of the string.
See
the CharAt(), Extract(), IndexOf(), Insert(), LastIndexOf(), Remove(), Replace(),
Substrings
Reverse(), and Substring() methods. See also the STRPOS, STRPUT,
and STRMID routines.
Splitting and The Split() method is used to break strings apart, and the Join() method can be
Joining used to join them. See also the STRSPLIT and STRJOIN functions.
The "EQ" operator can be used to directly compare two strings.
Comparing The Contains(), EndsWith(), Matches(), and StartsWith() methods can be used to
Strings compare portions of strings. See also the STRCMP, STRMATCH,
and STREGEX functions.

Q3b: What is the use of sparse matrix? Explain how sparse matrix is different from
normal Matrix? Discuss.

What is Sparse Matrix?


In computer programming, a matrix can be defined with a 2-dimensional array. Any array with
'm' columns and 'n' rows represent a m X n 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.
Sparse matrix is a matrix which contains very few non-zero elements.
When a sparse matrix is represented with a 2-dimensional array, we waste a 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 the matrix are filled with zero. That means, totally we allocate 100 X 100 X 2 = 20000
bytes of space to store this integer matrix. And to access these 10 non-zero elements we have to
make scanning for 10000 times. To make it simple we use the following sparse matrix
representation.

Sparse Matrix Representations


A sparse matrix can be represented by using TWO representations, those are as follows...

1. Triplet Representation (Array Representation)


2. Linked Representation

Triplet Representation (Array 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 the total number of rows, total number of
columns and the total number of non-zero values in the sparse 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 image...

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. The second row is filled with 0, 4, & 9 which indicates the
non-zero value 9 is at the 0th-row 4th column in the Sparse matrix. In the same way, the
remaining non-zero values also follow a similar pattern.

Q4a: What do you understand by D Queue? Discuss D -Queue with the help of
suitable example.
Ans:
A Deque or deck is a double-ended queue.
It is also known as “Head-Tail Linked List”
Allows elements to be added or removed on either the ends.
Dequeue can be implemented using Circular Array or a Circular doubly linked list where
Dequeue[n-1] is followed by Dequeue[0]
void insert_left()
{
int added_item;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
if ((right+1)%MAX==left)
{ printf("The queue is Full\n");
}
else if(left==-1 && right==-1)
{ printf("The queue is Empty\n");
left=right=0;
deque_arr[left]=added_item;
}
else if(left== 0)
{ left=MAX-1;
deque_arr[left] = added_item ;
}
else
{
left=left-1;
deque_arr[left] = added_item ;
}}

Q 4 b: What do you understand by PUSH and POP Operation? Discuss the tower of Hanoiproblem in
detail.
Ans. PUSH operation:
In a stack, push() is a function used to insert an element into the stack. In a stack, the new element is always
inserted at top position. Push function takes one integer value as parameter and inserts that value into the stack.
We can use the following steps to push an element on to the stack...
 Step 1 - Check whether stack is FULL. (top == SIZE-1)
 Step 2 - If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and terminate the function.
 Step 3 - If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value (stack[top] =
value).
POP Operation:
pop() - Delete a value from the Stack using array
In a stack, pop() is a function used to delete an element from the stack. In a stack, the element is always deleted
from top position. Pop function does not take any value as parameter. We can use the following steps to pop an
element from the stack...
 Step 1 - Check whether stack is EMPTY. (top == -1)
 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 delete stack[top] and decrement top value by one (top--).

TOH Problem:

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. 1. one disk at a
time. 2 top of the disk can be poped 3. no big disk on top of smaller disk
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest
The objective of the puzzle is to move the entire stack to another rod, obeying the following
simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Q 5 a: Sort the following data with the help of Heap sorting and write the Pseudo Code for
the above: {23,10,16,11,20}
Heap Sort Algorithm:
void heapify(int arr[], int n, int i)
{ int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;
// if left child is larger than largest so far
if (l < n && arr[l] > arr[largest])
largest = l;
// if right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// if largest is not root
if (largest != i)
{
swap(arr[i], arr[largest]);
// recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n)
{
// build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// one by one extract an element from heap
for (int i=n-1; i>=0; i--)
{ // move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}

Q5b: Explain Extended binary tree. Discuss the Type of Binary tree in detail.
Ans: Types of binary tree:
• Complete binary tree
• Strictly binary tree
• Almost complete binary tree
• Extended Binary Tree
Q 6 a: Discuss the Kruskal Algorithm with the help of an example.
Ans:
Total cost of tree= 7+3+3+2+2
= 17 (minimum)

Q 6 b: What is minimum cost spanning tree with respect to data structure? Explain with
example.
Ans:
Shortest path algorithms
There are two algorithms which are being used for this purpose.
o Prim's Algorithm
o Kruskal's Algorithm

Q7a: What do you understand by B-Tree? Differentiate between B-Tree & B+ Tree.
Ans:
B-Tree:
B-Tree is known as a self-balancing tree as its nodes are sorted in the inorder traversal. In B-tree, a node can have more
than two children. B-tree has a height of logM N (Where ‘M’ is the order of tree and N is the number of nodes). And the
height is adjusted automatically at each update. In the B-tree data is sorted in a specific order, with the lowest value on
the left and the highest value on the right. To insert the data or key in B-tree is more complicated than a binary tree.
There are some conditions that must be hold by the B-Tree:
 All the leaf nodes of the B-tree must be at the same level.
 Above the leaf nodes of the B-tree, there should be no empty sub-trees.
 B- tree’s height should lie as low as possible.
B+ Tree
B+ tree eliminates the drawback B-tree used for indexing by storing data pointers only at the leaf nodes of the tree. Thus,
the structure of leaf nodes of a B+ tree is quite different from the structure of internal nodes of the B tree. It may be noted
here that, since data pointers are present only at the leaf nodes, the leaf nodes must necessarily store all the key values
along with their corresponding data pointers to the disk file block, in order to access them. Moreover, the leaf nodes are
linked to providing ordered access to the records. The leaf nodes, therefore form the first level of the index, with the
internal nodes forming the other levels of a multilevel index. Some of the key values of the leaf nodes also appear in the
internal nodes, to simply act as a medium to control the searching of a record.
Let’s see the difference between B-tree and B+ tree:

S.
NO B tree B+ tree

All internal and leaf nodes Only leaf nodes have data
1. have data pointers pointers

Since all keys are not All keys are at leaf nodes,
available at leaf, search often hence search is faster and
2. takes more time. accurate..

Duplicate of keys are


No duplicate of keys is maintained and all nodes are
3. maintained in the tree. present at leaf.

Insertion takes more time and Insertion is easier and the results are
4. it is not predictable sometimes. always the same.

Deletion of internal node is Deletion of any node is easy


very complex and tree has to because all node are found at
5. undergo lot of transformations. leaf.

Leaf nodes are not stored as Leaf nodes are stored as


6. structural linked list. structural linked list.

No redundant search keys are Redundant search keys may


7. present.. be present..

Q7 b: Explain Briefly: I. Linear Search II. Bubble sorting


Ans:
Linear Search:
A simple approach is to do a linear search, i.e
 Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
 If x matches with an element, return the index.
 If x doesn’t match with any of elements, return -1.
#include <stdio.h>

int search(int arr[], int n, int x)


{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}

// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);

// Function call
int result = search(arr, n, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}

Bubble Sort:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in
wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass
without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 124 58)
( 1 2 4 5 8 ) –> ( 124 58)
( 1 2 4 5 8 ) –> ( 124 58)
( 1 2 4 5 8 ) –> ( 124 58)

// C program for implementation of Bubble sort


#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)

// Last i elements are already in place


for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

You might also like