# What else can we do with heaps? Use the heap for sorting. Heapsort!

## Presentation on theme: "What else can we do with heaps? Use the heap for sorting. Heapsort!"— Presentation transcript:

What else can we do with heaps? Use the heap for sorting. Heapsort!

Basic Idea Given an unsorted array we use BuildHeap to convert it into a heap While(heap is not empty) –removeMin –The heap is one smaller but the array hasn't changed –Put the item just removed in the element just after the end of the heap At conclusion the array is sorted

HeapSort after BuildHeap 1 5 2 5639 11 1971223226814 8743 273599427771 3367 89 size = 26

HeapSort 1 5 2 5639 11 1971223226814 8743 273599427771 3367 89 size = 26 removeMin

HeapSort 2 5 3 56229 11 1971223896814 8743 273599427771 3367 size = 25 removeMin = 1 Not in heap now

HeapSort 2 5 3 56229 11 1971223896814 8743 273599427771 3367 1 size = 25 heap is 1 element smaller, smallest element is at end of array

HeapSort 2 5 3 56229 11 1971223896814 8743 273599427771 3367 1 size = 25 Now do it again!

HeapSort 3 5 9 562214 11 1971223896867 8743 273599427771 332 1 size = 24

HeapSort 5 5 9 1162214 33 1971223896867 8743 273599427771 32 1 size = 23

HeapSort 5 6 9 1172214 33 19421223896867 8743 27359971775 32 1 size = 22

HeapSort 6 7 9 1172214 33 19421223896867 8743 2735997155 32 1 size = 21

HeapSort 7 7 9 11122214 33 19427123896867 8743 273599655 32 1 size = 20

HeapSort 7 11 9 19122214 33 27427123896867 8743 99357655 32 1 size = 19

HeapSort 9 11 14 19122235 33 27427123896867 8743 9977655 32 1 size = 18

HeapSort 11 12 14 19422235 33 27997123896867 8743 977655 32 1 size = 17

HeapSort 12 19 14 27422235 33 43997123896867 8711 977655 32 1 size = 16

HeapSort 14 19 22 27422335 33 43997187896867 1211 977655 32 1 size = 15

HeapSort 19 27 22 33422335 67 43997187896814 1211 977655 32 1 size = 14

HeapSort 22 27 23 33426835 67 43997187891914 1211 977655 32 1 size = 13

HeapSort 23 27 35 33426889 67 43997187221914 1211 977655 32 1 size = 12

HeapSort 27 33 35 43426889 67 87997123221914 1211 977655 32 1 size = 11

HeapSort 33 42 35 43716889 67 87992723221914 1211 977655 32 1 size = 10

HeapSort 35 42 68 43719989 67 87332723221914 1211 977655 32 1 size = 9

HeapSort 42 43 68 67719989 87 35332723221914 1211 977655 32 1 size = 8

HeapSort 43 67 68 87719989 42 35332723221914 1211 977655 32 1 size = 7

HeapSort 67 71 68 87899943 42 35332723221914 1211 977655 32 1 size = 6

HeapSort 68 71 99 87896743 42 35332723221914 1211 977655 32 1 size = 5

HeapSort 71 87 99 89686743 42 35332723221914 1211 977655 32 1 size = 4

HeapSort 87 89 99 71686743 42 35332723221914 1211 977655 32 1 size = 3

HeapSort 89 99 87 71686743 42 35332723221914 1211 977655 32 1 size = 2

HeapSort 99 89 87 71686743 42 35332723221914 1211 977655 32 1 size = 1

Download ppt "What else can we do with heaps? Use the heap for sorting. Heapsort!"

Similar presentations