0% found this document useful (0 votes)
2 views

practical 5

This document outlines a practical exercise focused on implementing and comparing Insertion Sort and Heap Sort algorithms. Insertion Sort is efficient for small datasets and operates in-place, while Heap Sort is better suited for larger datasets with a consistent O(N log N) time complexity. The document includes definitions, working mechanisms, properties, real-world applications, pseudocode, and code implementations for both sorting algorithms.

Uploaded by

Bhavya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

practical 5

This document outlines a practical exercise focused on implementing and comparing Insertion Sort and Heap Sort algorithms. Insertion Sort is efficient for small datasets and operates in-place, while Heap Sort is better suited for larger datasets with a consistent O(N log N) time complexity. The document includes definitions, working mechanisms, properties, real-world applications, pseudocode, and code implementations for both sorting algorithms.

Uploaded by

Bhavya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

DOP – 30/01/25 DOS – 05/02/25

PRACTICAL 5
AIM: Implementation and comparison of Insertion sort and Heap sort algorithm.
THEORY:
Sorting is a fundamental operation in computer science used to arrange elements in a specific
order, typically ascending or descending. In this practical, we implement and compare two
sorting algorithms: Insertion Sort and Heap Sort. While Insertion Sort is simple and efficient for
small datasets, Heap Sort is more suitable for larger datasets due to its efficient time complexity.
Insertion Sort
Definition
Insertion Sort is a simple comparison-based sorting algorithm that builds the final sorted array
one element at a time by inserting elements into their correct position.
Working Mechanism
1. It starts with the second element, assuming the first element is already sorted.
2. The current element is compared with the elements in the sorted part (left side).
3. If the current element is smaller, it is shifted left until it reaches its correct position.
4. This process continues until all elements are sorted.
Properties of Insertion Sort
1. In-place Sorting: It does not require extra space for sorting, making it memory efficient
(O(1) space complexity).
2. Stable Sort: It preserves the order of equal elements, making it suitable for sorting records
with multiple fields.
3. Adaptive Nature: It performs well on nearly sorted data, reducing its time complexity to
O(N) in the best case.
4. Online Algorithm: It can sort data as it receives it, making it useful for real-time
applications.
Real-World Applications of Insertion Sort
• Sorting small datasets where efficiency is not a primary concern.
• Hand sorting techniques, like arranging playing cards.
• When data arrives sequentially and needs to be sorted in real-time (e.g., live leaderboard
updates).

Page | 34
CO23329
DOP – 30/01/25 DOS – 05/02/25

Heap Sort
Definition
Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure to
organize and sort elements. It follows the Heap Property, where the parent node is always
greater (max heap) or smaller (min heap) than its children.
Working Mechanism
1. Convert the array into a max heap (largest element at the root).
2. Swap the root (largest element) with the last element of the heap.
3. Reduce the heap size and apply heapify to maintain the heap property.
4. Repeat the process until the array is sorted.
Properties of Heap Sort
1. Comparison-Based Sorting: It compares elements to maintain the heap property.
2. Efficient Time Complexity: Unlike Insertion Sort, it has a consistent O(N log N)
complexity in all cases.
3. Not a Stable Sort: Heap Sort does not preserve the order of equal elements after sorting.
4. In-place Sorting: It sorts data within the same array without needing extra memory.
5. Non-Recursive Sorting: Although heapify is often implemented recursively, it can be
written iteratively to avoid extra function call overhead.
Real-World Applications of Heap Sort
• Priority Queues: Used in scheduling processes in operating systems.
• Graph Algorithms: Used in Dijkstra’s Shortest Path Algorithm and Prim’s Minimum
Spanning Tree.
• Data Streaming: Sorting large sets of real-time data efficiently.
• Heap-Based Data Structures: Used in implementations of heaps, priority queues, and job
scheduling.

INSERTION SORT ALGORITHM:


1. Start with an unsorted array of size n.
2. Iterate through each element from index 1 to n-1 (let’s call the current element key).
3. For each key, find the correct position for key in the sorted part of the array (to the left of
key)
Page | 35
CO23329
DOP – 30/01/25 DOS – 05/02/25

o Shift all elements greater than key one position to the right.
o Insert key into its correct position.
4. Repeat the above steps for all elements until the entire array is sorted.
PSEUDOCODE OF INSERTION SORT :
InsertionSort(arr, n):
for i = 1 to n-1:
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j=j-1
arr[j + 1] = key
FLOW CHART :

Page | 36
CO23329
DOP – 30/01/25 DOS – 05/02/25

HEAP SORT ALGORITHM:


1. Start with an unsorted array of size n.
o Build a max heap (a complete binary tree where each node is greater than or equal
to its children) from the array.
2. This is done by calling the heapify function starting from the last non-leaf node to the
root.
3. After building the max heap:
o Swap the root (maximum element) with the last element of the heap.
o Reduce the heap size by 1 (exclude the last element, which is now in its correct
position).
o Call heapify on the root to restore the heap property.
4. Repeat step 3 until the heap size becomes 1.
PSEUDOCODE OF HEAP SORT:
HeapSort(arr, n):
// Step 1: Build max heap
for i = n/2 - 1 down to 0:
heapify(arr, n, i)

// Step 2: Extract elements one by one


for i = n-1 down to 1:
swap(arr[0], arr[i]) // Move current root to the end
heapify(arr, i, 0) // Call max heapify on the reduced heap

Heapify(arr, n, i):
largest = i
left = 2*i + 1
right = 2*i + 2

Page | 37
CO23329
DOP – 30/01/25 DOS – 05/02/25

if left < n and arr[left] > arr[largest]:


largest = left
if right < n and arr[right] > arr[largest]:
largest = right

if largest != i:
swap(arr[i], arr[largest])
heapify(arr, n, largest)
FLOW CHART:

CODE IMPLEMENTATION:
#include <iostream>
using namespace std;

Page | 38
CO23329
DOP – 30/01/25 DOS – 05/02/25

// Function for Insertion Sort


void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int info = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > info) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = info;
}
}

// Function to heapify a subtree rooted at index i


void heapify(int arr[], int n, int i) {
int max = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[max])


max = left;
if (right < n && arr[right] > arr[max])
max = right;

if (max != i) {
swap(arr[i], arr[max]);
heapify(arr, n, max);
}

Page | 39
CO23329
DOP – 30/01/25 DOS – 05/02/25

// Function for Heap Sort


void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

for (int i = n - 1; i > 0; i--) {


swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}

// Function to print an array


void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
int n, choice;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];

cout << "Enter the elements: ";


for (int i = 0; i < n; i++) {

Page | 40
CO23329
DOP – 30/01/25 DOS – 05/02/25

cin >> arr[i];


}

cout << "Choose sorting algorithm:\n";


cout << "1. Insertion Sort\n";
cout << "2. Heap Sort\n";
cout << "Enter choice: ";
cin >> choice;

switch (choice) {
case 1:
insertionSort(arr, n);
cout << "Sorted array using Insertion Sort: ";
break;
case 2:
heapSort(arr, n);
cout << "Sorted array using Heap Sort: ";
break;
default:
cout << "Invalid choice!";
return 1;
}

printArray(arr, n);
return 0;
}

Page | 41
CO23329
DOP – 30/01/25 DOS – 05/02/25

OUTPUT:

Page | 42
CO23329

You might also like