SlideShare a Scribd company logo
1 of 56
Download to read offline
HEAP SORT
Sunawar Khan
International Islamic University
Islamabad
January 04, 2016
INTRODUCTION
• What is Full Binary Tree
◦ Binary tree in which each node is either a leaf or has degree exactly 2.
2 of 26
INTRODUCTION
• What is Full Binary Tree
◦ Binary tree in which each node is either a leaf or has degree exactly 2.
• What is Complete binary tree
◦ Binary tree in which all leaves are on the same level and all internal
nodes have degree 2
2 of 26
INTRODUCTION
• What is Full Binary Tree
◦ Binary tree in which each node is either a leaf or has degree exactly 2.
• What is Complete binary tree
◦ Binary tree in which all leaves are on the same level and all internal
nodes have degree 2
• What is Heap Sort
◦ Combines the better attributes of merge sort and insertion sort.
• Like merge sort, but unlike insertion sort, running time is O(nlgn).
• Like insertion sort, but unlike merge sort, sorts in place.
2 of 26
INTRODUCTION
• What is Full Binary Tree
◦ Binary tree in which each node is either a leaf or has degree exactly 2.
• What is Complete binary tree
◦ Binary tree in which all leaves are on the same level and all internal
nodes have degree 2
• What is Heap Sort
◦ Combines the better attributes of merge sort and insertion sort.
• Like merge sort, but unlike insertion sort, running time is O(nlgn).
• Like insertion sort, but unlike merge sort, sorts in place.
◦ Introduces an algorithm design technique
• Create data structure (heap) to manage information during the
execution of an algorithm.
2 of 26
INTRODUCTION
• What is Full Binary Tree
◦ Binary tree in which each node is either a leaf or has degree exactly 2.
• What is Complete binary tree
◦ Binary tree in which all leaves are on the same level and all internal
nodes have degree 2
• What is Heap Sort
◦ Combines the better attributes of merge sort and insertion sort.
• Like merge sort, but unlike insertion sort, running time is O(nlgn).
• Like insertion sort, but unlike merge sort, sorts in place.
◦ Introduces an algorithm design technique
• Create data structure (heap) to manage information during the
execution of an algorithm.
◦ The heap has other applications beside sorting.
• Priority Queues
2 of 26
HEAP-Example
3 of 26
What is Heap-Properties
• Properties of Heap is
◦ Completeness Property
◦ Order Proprty
4 of 26
What is Heap-Properties
• Properties of Heap is
◦ Completeness Property
◦ Order Proprty
• Types of Heap is
◦ Max Heap
A[PARENT(i)] A[i]
◦ Min Heap
A[PARENT(i)] ≤ A[i]
4 of 26
What is Heap-Properties
• Properties of Heap is
◦ Completeness Property
◦ Order Proprty
• Types of Heap is
◦ Max Heap
A[PARENT(i)] A[i]
◦ Min Heap
A[PARENT(i)] ≤ A[i]
4 of 26
HEAP Properties Example
5 of 26
What is Heap-Characteristic
• Height of a node = the number of edges on the longest simple
path from the node down to a leaf lgn .
6 of 26
What is Heap-Characteristic
• Height of a node = the number of edges on the longest simple
path from the node down to a leaf lgn .
• Level of a node = the length of a path from the root to the node.
n/2 .
6 of 26
What is Heap-Characteristic
• Height of a node = the number of edges on the longest simple
path from the node down to a leaf lgn .
• Level of a node = the length of a path from the root to the node.
n/2 .
• Height of tree = height of root node. height h ≤ n/2h + 1
6 of 26
Heap Representations
• Heap can Be Represented As
◦ Root of tree is A[1]
7 of 26
Heap Representations
• Heap can Be Represented As
◦ Root of tree is A[1]
◦ Left
A[i] = A[2i]
7 of 26
Heap Representations
• Heap can Be Represented As
◦ Root of tree is A[1]
◦ Left
A[i] = A[2i]
◦ Right
A[i] = A[2i + 1]
7 of 26
Heap Representations
• Heap can Be Represented As
◦ Root of tree is A[1]
◦ Left
A[i] = A[2i]
◦ Right
A[i] = A[2i + 1]
◦ Parent
A[i] = A[ i/2 ]
7 of 26
Heap Representations
• Heap can Be Represented As
◦ Root of tree is A[1]
◦ Left
A[i] = A[2i]
◦ Right
A[i] = A[2i + 1]
◦ Parent
A[i] = A[ i/2 ]
◦ Heapsize[A] ≤ Length[A]
7 of 26
Problems
• What are the minimum and maximum numbers of elements in a
heap of height h?
• Show that an n-element heap has height lgn .
• Where in a max-heap might the smallest element reside, assuming
that all elements are distinct?
• Is an array that is in sorted order a min-heap?
• Is the array with values 23, 17, 14, 6, 13, 10, 1, 5, 7, 12 a
max-heap?
8 of 26
Maintaining The Heap Property
MAXIMUM-HEAPIFY PROCEDURE
MAX-HEAPIFY(A,i )
1. l ← LEFT(i)
2. r ← RIGHT(i)
3. if l ≤ A.heap-size and A[l]>A[i]
4. largest ← l
5. else largest ← i
6. if r ≤ A.heap-size and A[r]>A[largest]
7. largest ← r
8. if largest ← i
9. exchange A[i] ↔ A[largest]
10. MAX-HEAPIFY(A, largest)
9 of 26
Maintain Heap Example
10 of 26
Running Time of MAX-HEAPIFY
• Running time of MAX-HEAPIFY is O(lgn)
11 of 26
Running Time of MAX-HEAPIFY
• Running time of MAX-HEAPIFY is O(lgn)
• Can be written in terms of the height of the heap, as being O(h)
Since the height of the heap is lgn
11 of 26
Running Time of MAX-HEAPIFY
• Running time of MAX-HEAPIFY is O(lgn)
• Can be written in terms of the height of the heap, as being O(h)
Since the height of the heap is lgn
• MaxHeapify takes O(h) where h is the height of the node where
MaxHeapify is applied.
T(n) = O(lgn)
11 of 26
Problems
• What is the effect of calling MAX-HEAPIFY(A, i) when the
element A[i] is larger than its children?
• What is the effect of calling MAX-HEAPIFY(A, i) for
i>A.heap-size/2?
• Show that the worst-case running time of MAX-HEAPIFY on a
heap of size n is Ω(lgn).
12 of 26
Building a heap
Building Max Heap PROCEDURE
BuildMaxHeap(A)
1. heap-size[A] ← length[A]
2. for i ← length[A]/2 downto 1
3. do MaxHeapify(A, i)
13 of 26
Build Heap-Example
14 of 26
Running Time of Build-Heap
• Running time: O(nlgn)
This is not an asymptotically tight upper bound
15 of 26
HEAP SORT
• Goal:
◦ Sort an array using heap representations
16 of 26
HEAP SORT
• Goal:
◦ Sort an array using heap representations
• Idea:
◦ Build a max-heap from the array
◦ Swap the root (the maximum element) with the last element in the
array
◦ Discard this last node by decreasing the heap size
◦ Call MAX-HEAPIFY on the new root
◦ Repeat this process until only one node remains
16 of 26
HEAP SORT PROCEDURE
• Sort by maintaining the as yet unsorted elements as a max-heap.
17 of 26
HEAP SORT PROCEDURE
• Sort by maintaining the as yet unsorted elements as a max-heap.
• Start by building a max-heap on all elements in A.
17 of 26
HEAP SORT PROCEDURE
• Sort by maintaining the as yet unsorted elements as a max-heap.
• Start by building a max-heap on all elements in A.
Maximum element is in the root, A[1].
17 of 26
HEAP SORT PROCEDURE
• Sort by maintaining the as yet unsorted elements as a max-heap.
• Start by building a max-heap on all elements in A.
Maximum element is in the root, A[1].
• Move the maximum element to its correct final position.
Exchange A[1] with A[n].
17 of 26
HEAP SORT PROCEDURE
• Sort by maintaining the as yet unsorted elements as a max-heap.
• Start by building a max-heap on all elements in A.
Maximum element is in the root, A[1].
• Move the maximum element to its correct final position.
Exchange A[1] with A[n].
• Discard A[n] it is now sorted.
Decrement heap-size[A].
17 of 26
HEAP SORT PROCEDURE
• Sort by maintaining the as yet unsorted elements as a max-heap.
• Start by building a max-heap on all elements in A.
Maximum element is in the root, A[1].
• Move the maximum element to its correct final position.
Exchange A[1] with A[n].
• Discard A[n] it is now sorted.
Decrement heap-size[A].
• Restore the max-heap property on A[1..n1].
Call MaxHeapify(A, 1).
17 of 26
HEAP SORT PROCEDURE
• Sort by maintaining the as yet unsorted elements as a max-heap.
• Start by building a max-heap on all elements in A.
Maximum element is in the root, A[1].
• Move the maximum element to its correct final position.
Exchange A[1] with A[n].
• Discard A[n] it is now sorted.
Decrement heap-size[A].
• Restore the max-heap property on A[1..n1].
Call MaxHeapify(A, 1).
• Repeat until heap-size[A] is reduced to 2.
17 of 26
HEAP SORT
// Input: A: an (unsorted) array
// Output: A modifed to be sorted from smallest to largest
// Running Time: O(nlogn) where n = length[A]
HeapSort(A)
1. Build-Max-Heap(A)
2. for i ← length[A] downto 2
3. do exchange A[1] ↔ A[i]
4. heap-size[A] ← heap-size[A] 1
5. MaxHeapify(A, 1)
18 of 26
Heap Sort Example
19 of 26
Running Time for Heap Sort
• Build-Max-Heap takes O(n) and each of the n-1 calls to
Max-Heapify takes time O(lgn).
T(n) = O(nlgn)
20 of 26
Running Time for Heap Sort
• Build-Max-Heap takes O(n) and each of the n-1 calls to
Max-Heapify takes time O(lgn).
T(n) = O(nlgn)
• The heap sorting algorithm uses two procedures : BUILD-HEAP
and HEAPIFY. Thus, total running time Tsort(n) to sort an array
of size n is
20 of 26
Problems
• What is the running time of HEAPSORT on an array A of length n
that is already sorted in increasing order? What about decreasing
order?
• Show that the worst-case running time of HEAPSORT is Ω(nlgn).
21 of 26
Complexity
• To insert a single node in an empty heap is : O(1).
• To insert a single element in a n node heap is : O(logn).
• To insert n elements in a n node heap is : O(nlogn).
• To delete the largest element in a max heap tree : O(1).
• To delete the smallest element in a max heap tree : O(logn).
• To delete n elements in a max heap tree : O(nlogn).
• To create a heap, time complexity will be : O(nlogn).
22 of 26
Complexity
Now to sort the heap tree requires
• Arrange or insert the elements in a form of heap i.e O(nlogn)
• Delete the elements one by one after swapping operation O(nlogn)
• This gives Heap sort complexity
O(nlogn) + O(nlogn)
2O(nlogn) = O(nlogn).
23 of 26
Heap Procedures for Sorting
• MaxHeapify O(lgn)
24 of 26
Heap Procedures for Sorting
• MaxHeapify O(lgn)
• BuildMaxHeap O(n)
24 of 26
Heap Procedures for Sorting
• MaxHeapify O(lgn)
• BuildMaxHeap O(n)
• HeapSort O(nlgn)
24 of 26
SUMMARY
• We can perform the following operations on heaps:
◦ MAX-HEAPIFY O(lgn)
25 of 26
SUMMARY
• We can perform the following operations on heaps:
◦ MAX-HEAPIFY O(lgn)
◦ BUILD-MAX-HEAP O(n)
25 of 26
SUMMARY
• We can perform the following operations on heaps:
◦ MAX-HEAPIFY O(lgn)
◦ BUILD-MAX-HEAP O(n)
◦ HEAP-SORT O(nlgn)
25 of 26
SUMMARY
• We can perform the following operations on heaps:
◦ MAX-HEAPIFY O(lgn)
◦ BUILD-MAX-HEAP O(n)
◦ HEAP-SORT O(nlgn)
◦ MAX-HEAP-INSERT O(lgn)
25 of 26
SUMMARY
• We can perform the following operations on heaps:
◦ MAX-HEAPIFY O(lgn)
◦ BUILD-MAX-HEAP O(n)
◦ HEAP-SORT O(nlgn)
◦ MAX-HEAP-INSERT O(lgn)
◦ HEAP-EXTRACT-MAX O(lgn)
25 of 26
SUMMARY
• We can perform the following operations on heaps:
◦ MAX-HEAPIFY O(lgn)
◦ BUILD-MAX-HEAP O(n)
◦ HEAP-SORT O(nlgn)
◦ MAX-HEAP-INSERT O(lgn)
◦ HEAP-EXTRACT-MAX O(lgn)
◦ HEAP-INCREASE-KEY O(lgn)
25 of 26
SUMMARY
• We can perform the following operations on heaps:
◦ MAX-HEAPIFY O(lgn)
◦ BUILD-MAX-HEAP O(n)
◦ HEAP-SORT O(nlgn)
◦ MAX-HEAP-INSERT O(lgn)
◦ HEAP-EXTRACT-MAX O(lgn)
◦ HEAP-INCREASE-KEY O(lgn)
◦ HEAP-MAXIMUM O(1)
25 of 26
Building a heap
• Presented To:- Dr. Arshad Aewan
• Presented By:- SK Ahsan
• Reg No:- 813/FBAS/MSCS/F14
• Topic:- Heap Sort(Procedure)
• My Dreams Are My Own Drems(Me)
26 of 26

More Related Content

What's hot

Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmssamairaakram
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESSowmya Jyothi
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]Muhammad Hammad Waseem
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort AlgorithmLemia Algmri
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked ListReazul Islam
 
Data Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and TreesData Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and TreesManishPrajapati78
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Muhammad Hammad Waseem
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structureghhgj jhgh
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structureMAHALAKSHMI P
 
Presentation on Heap Sort
Presentation on Heap Sort Presentation on Heap Sort
Presentation on Heap Sort Amit Kundu
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - NotesOmprakash Chauhan
 
Priority queue in DSA
Priority queue in DSAPriority queue in DSA
Priority queue in DSAjunnubabu
 

What's hot (20)

Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
Heaps
HeapsHeaps
Heaps
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Heapsort ppt
Heapsort pptHeapsort ppt
Heapsort ppt
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked List
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Data Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and TreesData Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and Trees
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
stack presentation
stack presentationstack presentation
stack presentation
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
Presentation on Heap Sort
Presentation on Heap Sort Presentation on Heap Sort
Presentation on Heap Sort
 
Queue
QueueQueue
Queue
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - Notes
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Priority queue in DSA
Priority queue in DSAPriority queue in DSA
Priority queue in DSA
 

Similar to Heap sort

Heaps and tries power point this is an educational material
Heaps and tries power point this is an educational materialHeaps and tries power point this is an educational material
Heaps and tries power point this is an educational materialAymericTaylor
 
Lecture 07 - HeapSort.pptx
Lecture 07 - HeapSort.pptxLecture 07 - HeapSort.pptx
Lecture 07 - HeapSort.pptxIsrar63
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sortKrish_ver2
 
Analysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortAnalysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortReetesh Gupta
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisRadhika Talaviya
 
splaytree-171227043127.pptx NNNNNNNNNNNNNNNNNNNNNNN
splaytree-171227043127.pptx NNNNNNNNNNNNNNNNNNNNNNNsplaytree-171227043127.pptx NNNNNNNNNNNNNNNNNNNNNNN
splaytree-171227043127.pptx NNNNNNNNNNNNNNNNNNNNNNNratnapatil14
 
Heap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmHeap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmLearning Courses Online
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).pptAmitShou
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).pptSudhaPatel11
 

Similar to Heap sort (20)

Heaps and tries power point this is an educational material
Heaps and tries power point this is an educational materialHeaps and tries power point this is an educational material
Heaps and tries power point this is an educational material
 
Lecture 07 - HeapSort.pptx
Lecture 07 - HeapSort.pptxLecture 07 - HeapSort.pptx
Lecture 07 - HeapSort.pptx
 
Heapsort
HeapsortHeapsort
Heapsort
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
 
Analysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortAnalysis of Algorithms-Heapsort
Analysis of Algorithms-Heapsort
 
Heapsort
HeapsortHeapsort
Heapsort
 
Heapsort
HeapsortHeapsort
Heapsort
 
HEAP SORT .pptx
HEAP SORT .pptxHEAP SORT .pptx
HEAP SORT .pptx
 
Sorting
SortingSorting
Sorting
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
 
sparse set.pdf
sparse set.pdfsparse set.pdf
sparse set.pdf
 
Algorithms - "heap sort"
Algorithms - "heap sort"Algorithms - "heap sort"
Algorithms - "heap sort"
 
Splay tree
Splay treeSplay tree
Splay tree
 
splaytree-171227043127.pptx NNNNNNNNNNNNNNNNNNNNNNN
splaytree-171227043127.pptx NNNNNNNNNNNNNNNNNNNNNNNsplaytree-171227043127.pptx NNNNNNNNNNNNNNNNNNNNNNN
splaytree-171227043127.pptx NNNNNNNNNNNNNNNNNNNNNNN
 
Heap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmHeap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap Algorithm
 
heaps2
heaps2heaps2
heaps2
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
heapsort_bydinesh
heapsort_bydineshheapsort_bydinesh
heapsort_bydinesh
 

More from International Islamic University (20)

Hash tables
Hash tablesHash tables
Hash tables
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Graph 1
Graph 1Graph 1
Graph 1
 
Graph 2
Graph 2Graph 2
Graph 2
 
Graph 3
Graph 3Graph 3
Graph 3
 
Greedy algorithm
Greedy algorithmGreedy algorithm
Greedy algorithm
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Quick sort
Quick sortQuick sort
Quick sort
 
Merge sort
Merge sortMerge sort
Merge sort
 
Linear timesorting
Linear timesortingLinear timesorting
Linear timesorting
 
Facial Expression Recognitino
Facial Expression RecognitinoFacial Expression Recognitino
Facial Expression Recognitino
 
Lecture#4
Lecture#4Lecture#4
Lecture#4
 
Lecture#3
Lecture#3 Lecture#3
Lecture#3
 
Lecture#2
Lecture#2 Lecture#2
Lecture#2
 
Case study
Case studyCase study
Case study
 
Arrays
ArraysArrays
Arrays
 
Pcb
PcbPcb
Pcb
 
Data transmission
Data transmissionData transmission
Data transmission
 
Basic organization of computer
Basic organization of computerBasic organization of computer
Basic organization of computer
 
Sorting techniques
Sorting techniquesSorting techniques
Sorting techniques
 

Recently uploaded

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 

Recently uploaded (20)

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Heap sort

  • 1. HEAP SORT Sunawar Khan International Islamic University Islamabad January 04, 2016
  • 2. INTRODUCTION • What is Full Binary Tree ◦ Binary tree in which each node is either a leaf or has degree exactly 2. 2 of 26
  • 3. INTRODUCTION • What is Full Binary Tree ◦ Binary tree in which each node is either a leaf or has degree exactly 2. • What is Complete binary tree ◦ Binary tree in which all leaves are on the same level and all internal nodes have degree 2 2 of 26
  • 4. INTRODUCTION • What is Full Binary Tree ◦ Binary tree in which each node is either a leaf or has degree exactly 2. • What is Complete binary tree ◦ Binary tree in which all leaves are on the same level and all internal nodes have degree 2 • What is Heap Sort ◦ Combines the better attributes of merge sort and insertion sort. • Like merge sort, but unlike insertion sort, running time is O(nlgn). • Like insertion sort, but unlike merge sort, sorts in place. 2 of 26
  • 5. INTRODUCTION • What is Full Binary Tree ◦ Binary tree in which each node is either a leaf or has degree exactly 2. • What is Complete binary tree ◦ Binary tree in which all leaves are on the same level and all internal nodes have degree 2 • What is Heap Sort ◦ Combines the better attributes of merge sort and insertion sort. • Like merge sort, but unlike insertion sort, running time is O(nlgn). • Like insertion sort, but unlike merge sort, sorts in place. ◦ Introduces an algorithm design technique • Create data structure (heap) to manage information during the execution of an algorithm. 2 of 26
  • 6. INTRODUCTION • What is Full Binary Tree ◦ Binary tree in which each node is either a leaf or has degree exactly 2. • What is Complete binary tree ◦ Binary tree in which all leaves are on the same level and all internal nodes have degree 2 • What is Heap Sort ◦ Combines the better attributes of merge sort and insertion sort. • Like merge sort, but unlike insertion sort, running time is O(nlgn). • Like insertion sort, but unlike merge sort, sorts in place. ◦ Introduces an algorithm design technique • Create data structure (heap) to manage information during the execution of an algorithm. ◦ The heap has other applications beside sorting. • Priority Queues 2 of 26
  • 8. What is Heap-Properties • Properties of Heap is ◦ Completeness Property ◦ Order Proprty 4 of 26
  • 9. What is Heap-Properties • Properties of Heap is ◦ Completeness Property ◦ Order Proprty • Types of Heap is ◦ Max Heap A[PARENT(i)] A[i] ◦ Min Heap A[PARENT(i)] ≤ A[i] 4 of 26
  • 10. What is Heap-Properties • Properties of Heap is ◦ Completeness Property ◦ Order Proprty • Types of Heap is ◦ Max Heap A[PARENT(i)] A[i] ◦ Min Heap A[PARENT(i)] ≤ A[i] 4 of 26
  • 12. What is Heap-Characteristic • Height of a node = the number of edges on the longest simple path from the node down to a leaf lgn . 6 of 26
  • 13. What is Heap-Characteristic • Height of a node = the number of edges on the longest simple path from the node down to a leaf lgn . • Level of a node = the length of a path from the root to the node. n/2 . 6 of 26
  • 14. What is Heap-Characteristic • Height of a node = the number of edges on the longest simple path from the node down to a leaf lgn . • Level of a node = the length of a path from the root to the node. n/2 . • Height of tree = height of root node. height h ≤ n/2h + 1 6 of 26
  • 15. Heap Representations • Heap can Be Represented As ◦ Root of tree is A[1] 7 of 26
  • 16. Heap Representations • Heap can Be Represented As ◦ Root of tree is A[1] ◦ Left A[i] = A[2i] 7 of 26
  • 17. Heap Representations • Heap can Be Represented As ◦ Root of tree is A[1] ◦ Left A[i] = A[2i] ◦ Right A[i] = A[2i + 1] 7 of 26
  • 18. Heap Representations • Heap can Be Represented As ◦ Root of tree is A[1] ◦ Left A[i] = A[2i] ◦ Right A[i] = A[2i + 1] ◦ Parent A[i] = A[ i/2 ] 7 of 26
  • 19. Heap Representations • Heap can Be Represented As ◦ Root of tree is A[1] ◦ Left A[i] = A[2i] ◦ Right A[i] = A[2i + 1] ◦ Parent A[i] = A[ i/2 ] ◦ Heapsize[A] ≤ Length[A] 7 of 26
  • 20. Problems • What are the minimum and maximum numbers of elements in a heap of height h? • Show that an n-element heap has height lgn . • Where in a max-heap might the smallest element reside, assuming that all elements are distinct? • Is an array that is in sorted order a min-heap? • Is the array with values 23, 17, 14, 6, 13, 10, 1, 5, 7, 12 a max-heap? 8 of 26
  • 21. Maintaining The Heap Property MAXIMUM-HEAPIFY PROCEDURE MAX-HEAPIFY(A,i ) 1. l ← LEFT(i) 2. r ← RIGHT(i) 3. if l ≤ A.heap-size and A[l]>A[i] 4. largest ← l 5. else largest ← i 6. if r ≤ A.heap-size and A[r]>A[largest] 7. largest ← r 8. if largest ← i 9. exchange A[i] ↔ A[largest] 10. MAX-HEAPIFY(A, largest) 9 of 26
  • 23. Running Time of MAX-HEAPIFY • Running time of MAX-HEAPIFY is O(lgn) 11 of 26
  • 24. Running Time of MAX-HEAPIFY • Running time of MAX-HEAPIFY is O(lgn) • Can be written in terms of the height of the heap, as being O(h) Since the height of the heap is lgn 11 of 26
  • 25. Running Time of MAX-HEAPIFY • Running time of MAX-HEAPIFY is O(lgn) • Can be written in terms of the height of the heap, as being O(h) Since the height of the heap is lgn • MaxHeapify takes O(h) where h is the height of the node where MaxHeapify is applied. T(n) = O(lgn) 11 of 26
  • 26. Problems • What is the effect of calling MAX-HEAPIFY(A, i) when the element A[i] is larger than its children? • What is the effect of calling MAX-HEAPIFY(A, i) for i>A.heap-size/2? • Show that the worst-case running time of MAX-HEAPIFY on a heap of size n is Ω(lgn). 12 of 26
  • 27. Building a heap Building Max Heap PROCEDURE BuildMaxHeap(A) 1. heap-size[A] ← length[A] 2. for i ← length[A]/2 downto 1 3. do MaxHeapify(A, i) 13 of 26
  • 29. Running Time of Build-Heap • Running time: O(nlgn) This is not an asymptotically tight upper bound 15 of 26
  • 30. HEAP SORT • Goal: ◦ Sort an array using heap representations 16 of 26
  • 31. HEAP SORT • Goal: ◦ Sort an array using heap representations • Idea: ◦ Build a max-heap from the array ◦ Swap the root (the maximum element) with the last element in the array ◦ Discard this last node by decreasing the heap size ◦ Call MAX-HEAPIFY on the new root ◦ Repeat this process until only one node remains 16 of 26
  • 32. HEAP SORT PROCEDURE • Sort by maintaining the as yet unsorted elements as a max-heap. 17 of 26
  • 33. HEAP SORT PROCEDURE • Sort by maintaining the as yet unsorted elements as a max-heap. • Start by building a max-heap on all elements in A. 17 of 26
  • 34. HEAP SORT PROCEDURE • Sort by maintaining the as yet unsorted elements as a max-heap. • Start by building a max-heap on all elements in A. Maximum element is in the root, A[1]. 17 of 26
  • 35. HEAP SORT PROCEDURE • Sort by maintaining the as yet unsorted elements as a max-heap. • Start by building a max-heap on all elements in A. Maximum element is in the root, A[1]. • Move the maximum element to its correct final position. Exchange A[1] with A[n]. 17 of 26
  • 36. HEAP SORT PROCEDURE • Sort by maintaining the as yet unsorted elements as a max-heap. • Start by building a max-heap on all elements in A. Maximum element is in the root, A[1]. • Move the maximum element to its correct final position. Exchange A[1] with A[n]. • Discard A[n] it is now sorted. Decrement heap-size[A]. 17 of 26
  • 37. HEAP SORT PROCEDURE • Sort by maintaining the as yet unsorted elements as a max-heap. • Start by building a max-heap on all elements in A. Maximum element is in the root, A[1]. • Move the maximum element to its correct final position. Exchange A[1] with A[n]. • Discard A[n] it is now sorted. Decrement heap-size[A]. • Restore the max-heap property on A[1..n1]. Call MaxHeapify(A, 1). 17 of 26
  • 38. HEAP SORT PROCEDURE • Sort by maintaining the as yet unsorted elements as a max-heap. • Start by building a max-heap on all elements in A. Maximum element is in the root, A[1]. • Move the maximum element to its correct final position. Exchange A[1] with A[n]. • Discard A[n] it is now sorted. Decrement heap-size[A]. • Restore the max-heap property on A[1..n1]. Call MaxHeapify(A, 1). • Repeat until heap-size[A] is reduced to 2. 17 of 26
  • 39. HEAP SORT // Input: A: an (unsorted) array // Output: A modifed to be sorted from smallest to largest // Running Time: O(nlogn) where n = length[A] HeapSort(A) 1. Build-Max-Heap(A) 2. for i ← length[A] downto 2 3. do exchange A[1] ↔ A[i] 4. heap-size[A] ← heap-size[A] 1 5. MaxHeapify(A, 1) 18 of 26
  • 41. Running Time for Heap Sort • Build-Max-Heap takes O(n) and each of the n-1 calls to Max-Heapify takes time O(lgn). T(n) = O(nlgn) 20 of 26
  • 42. Running Time for Heap Sort • Build-Max-Heap takes O(n) and each of the n-1 calls to Max-Heapify takes time O(lgn). T(n) = O(nlgn) • The heap sorting algorithm uses two procedures : BUILD-HEAP and HEAPIFY. Thus, total running time Tsort(n) to sort an array of size n is 20 of 26
  • 43. Problems • What is the running time of HEAPSORT on an array A of length n that is already sorted in increasing order? What about decreasing order? • Show that the worst-case running time of HEAPSORT is Ω(nlgn). 21 of 26
  • 44. Complexity • To insert a single node in an empty heap is : O(1). • To insert a single element in a n node heap is : O(logn). • To insert n elements in a n node heap is : O(nlogn). • To delete the largest element in a max heap tree : O(1). • To delete the smallest element in a max heap tree : O(logn). • To delete n elements in a max heap tree : O(nlogn). • To create a heap, time complexity will be : O(nlogn). 22 of 26
  • 45. Complexity Now to sort the heap tree requires • Arrange or insert the elements in a form of heap i.e O(nlogn) • Delete the elements one by one after swapping operation O(nlogn) • This gives Heap sort complexity O(nlogn) + O(nlogn) 2O(nlogn) = O(nlogn). 23 of 26
  • 46. Heap Procedures for Sorting • MaxHeapify O(lgn) 24 of 26
  • 47. Heap Procedures for Sorting • MaxHeapify O(lgn) • BuildMaxHeap O(n) 24 of 26
  • 48. Heap Procedures for Sorting • MaxHeapify O(lgn) • BuildMaxHeap O(n) • HeapSort O(nlgn) 24 of 26
  • 49. SUMMARY • We can perform the following operations on heaps: ◦ MAX-HEAPIFY O(lgn) 25 of 26
  • 50. SUMMARY • We can perform the following operations on heaps: ◦ MAX-HEAPIFY O(lgn) ◦ BUILD-MAX-HEAP O(n) 25 of 26
  • 51. SUMMARY • We can perform the following operations on heaps: ◦ MAX-HEAPIFY O(lgn) ◦ BUILD-MAX-HEAP O(n) ◦ HEAP-SORT O(nlgn) 25 of 26
  • 52. SUMMARY • We can perform the following operations on heaps: ◦ MAX-HEAPIFY O(lgn) ◦ BUILD-MAX-HEAP O(n) ◦ HEAP-SORT O(nlgn) ◦ MAX-HEAP-INSERT O(lgn) 25 of 26
  • 53. SUMMARY • We can perform the following operations on heaps: ◦ MAX-HEAPIFY O(lgn) ◦ BUILD-MAX-HEAP O(n) ◦ HEAP-SORT O(nlgn) ◦ MAX-HEAP-INSERT O(lgn) ◦ HEAP-EXTRACT-MAX O(lgn) 25 of 26
  • 54. SUMMARY • We can perform the following operations on heaps: ◦ MAX-HEAPIFY O(lgn) ◦ BUILD-MAX-HEAP O(n) ◦ HEAP-SORT O(nlgn) ◦ MAX-HEAP-INSERT O(lgn) ◦ HEAP-EXTRACT-MAX O(lgn) ◦ HEAP-INCREASE-KEY O(lgn) 25 of 26
  • 55. SUMMARY • We can perform the following operations on heaps: ◦ MAX-HEAPIFY O(lgn) ◦ BUILD-MAX-HEAP O(n) ◦ HEAP-SORT O(nlgn) ◦ MAX-HEAP-INSERT O(lgn) ◦ HEAP-EXTRACT-MAX O(lgn) ◦ HEAP-INCREASE-KEY O(lgn) ◦ HEAP-MAXIMUM O(1) 25 of 26
  • 56. Building a heap • Presented To:- Dr. Arshad Aewan • Presented By:- SK Ahsan • Reg No:- 813/FBAS/MSCS/F14 • Topic:- Heap Sort(Procedure) • My Dreams Are My Own Drems(Me) 26 of 26