Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
15 views5 pages

Heap Sort

The document introduces sorting algorithms, emphasizing their importance for efficient data processing. It explains the heap data structure, detailing max-heaps and min-heaps, and outlines the steps to build a max-heap from an unsorted array. Additionally, it provides a step-by-step description of the heap sort algorithm and includes a code example for the heapify function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views5 pages

Heap Sort

The document introduces sorting algorithms, emphasizing their importance for efficient data processing. It explains the heap data structure, detailing max-heaps and min-heaps, and outlines the steps to build a max-heap from an unsorted array. Additionally, it provides a step-by-step description of the heap sort algorithm and includes a code example for the heapify function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 5

Introduction to Sorting Alg

orithms and Their Importa


nce
Sorting Basics Common Algorithms
Sorting arranges data in a sp
ecific order for easy searchin • Bubble Sort
g and processing. • Merge Sort
• Heap Sort

Why It Matters
Efficient sorting improves performance in databases, apps, and more.
Understanding the Heap D
ata Structure
Heap Definition Max-Heap
A heap is a complete binar Parent nodes are always la
y tree with a special orderi rger than their children.
ng property.

Min-Heap
Parent nodes are smaller than their children.
Building a Max-Heap from
an Unsorted Array

Start from Bottom


Begin heapifying from the last non-leaf node upwards.

Heapify Subtrees
Ensure subtrees satisfy max-heap property by swapping node
s as needed.

Complete Heap
Finish when entire tree follows max-heap rules.
The Heap Sort Algorithm: Ste
p-by-Step
Build Max-Heap
Convert the array into a max-heap structure.

Swap Root
Exchange the root with the last element.

Reduce Heap
Reduce heap size, excluding the sorted elements.

Heapify
Restore max-heap property after each swap.
Heap Sort Code Example
void heapify(int arr[], int n, int i) {
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;

if (l < n && arr[l] > arr[largest])


largest = l;

if (r < n && arr[r] > arr[largest])


largest = r;

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

You might also like