>

>
1x
go to beginning previous frame pause play next frame go to end

A Binary (Max) Heap is a complete binary tree that maintains the Max Heap property.


Binary Heap is one possible data structure to model an efficient Priority Queue (PQ) Abstract Data Type (ADT). In a PQ, each element has a "priority" and an element with higher priority is served before an element with lower priority (ties are either simply resolved arbitrarily or broken with standard First-In First-Out (FIFO) rule as with a normal Queue). Try clicking ExtractMax() for a sample animation on extracting the max value of random Binary Heap above.


To focus the discussion scope, this visualization show a Binary Max Heap of integers where duplicates are allowed. See this for an easy conversion to Binary Min Heap. Generally, any other objects that can be compared can be stored in a Binary Max Heap, e.g., Binary Max Heap of floating points, etc.


Remarks: By default, we show e-Lecture Mode for first time (or non logged-in) visitor.
If you are an NUS student and a repeat visitor, please login.

🕑

Complete Binary Tree: Every level in the binary tree, except possibly the last/lowest level, is completely filled, and all vertices in the last level are as far left as possible.


Binary Max Heap property: The parent of each vertex - except the root - contains value greater than (or equal to — we now allow duplicates) the value of that vertex. This is an easier-to-verify definition than the following alternative definition: The value of a vertex - except the leaf/leaves - must be greater than (or equal to) the value of its one (or two) child(ren).


Pro-tip 1: Since you are not logged-in, you may be a first time visitor (or not an NUS student) who are not aware of the following keyboard shortcuts to navigate this e-Lecture mode: [PageDown]/[PageUp] to go to the next/previous slide, respectively, (and if the drop-down box is highlighted, you can also use [→ or ↓/← or ↑] to do the same),and [Esc] to toggle between this e-Lecture mode and exploration mode.

🕑

Priority Queue (PQ) Abstract Data Type (ADT) is similar to normal Queue ADT, but with these two major operations:

  1. Enqueue(x): Put a new element (key) x into the PQ (in some order),
  2. y = Dequeue(): Return an existing element y that has the highest priority (key) in the PQ and if ties, return any.

Discussion: Some PQ ADT reverts to First-In First-Out (FIFO) behavior of a normal Queue in the event there is a tie of highest priority (key) in the PQ. Does guaranteeing stability on equal highest priority (key) makes PQ ADT harder to implement?


Pro-tip 2: We designed this visualization and this e-Lecture mode to look good on 1366x768 resolution or larger (typical modern laptop resolution in 2021). We recommend using Google Chrome to access VisuAlgo. Go to full screen mode (F11) to enjoy this setup. However, you can use zoom-in (Ctrl +) or zoom-out (Ctrl -) to calibrate this.

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.


Pro-tip 3: Other than using the typical media UI at the bottom of the page, you can also control the animation playback using keyboard shortcuts (in Exploration Mode): Spacebar to play/pause/replay the animation, / to step the animation backwards/forwards, respectively, and -/+ to decrease/increase the animation speed, respectively.

🕑

Imagine: You are an Air Traffic Controller (ATC) working in the control tower T of an airport. You have scheduled aircraft X/Y to land in the next 3/6 minutes, respectively. Both have enough fuel for at least the next 15 minutes and both are just 2 minutes away from your airport. You observe that your airport runway is clear at the moment.



In case you do not know, aircraft can be instructed to fly in holding pattern near the airport until the designated landing time.

🕑

You have to attend the live lecture to figure out what happens next...


There will be two options presented to you and you will have to decide:

  • Raise AND wave your hand if you choose option A,
  • Raise your hand but do NOT wave it if you choose option B,

If none of the two options is reasonable for you, simply do nothing.

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

There are several potential usages of PQ ADT in real-life on top of what you have seen just now regarding ATC (only in live lecture).


Discussion: Can you mention a few other real-life situations where a PQ is needed?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

Kita bisa mengimplementasikan ADT PQ ini menggunakan larik (sirkular) atau Senarai Berantai (Linked List) tetapi kita akan mendapatkan operasi Enqueue atau Dequeue yang pelan (yaitu dalam O(N)).


Diskusi: Kenapa?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

Now, let's view the visualisation of a (random) Binary (Max) Heap above. You should see a complete binary tree and all vertices except the root satisfy the Max Heap property (A[parent(i)] ≥ A[i]). Duplicate integer keys may appear.


You can Toggle the Visualization Mode between the visually more intuitive complete binary tree form or the underlying compact array based implementation of a Binary (Max) Heap.


Quiz: Based on this Binary (Max) Heap property, where will the largest integer be located?

At the root
At one of the leaf
Can be anywhere
🕑

Fakta penting untuk dihafal saat ini: Jika kita memiliki Timbunan Biner dengan N elemen, tingginya tidak akan lebih tinggi dari O(log N) karena kita akan menaruhnya sebagai pohon biner komplet.


Analisa sederhana: Besarnya N dari sebuah pohon biner penuh (lebih dari sekedar komplet) dengan tinggi h adalah selalu N = 2(h+1)-1, sehingga h = log2(N+1)-1 ~= log2 N.


Lihat contoh diatas dengan N = 7 = 2(2+1)-1 or h = log2(7+1)-1 = 2.


Fakta ini penting untuk analisa dari semua operasi-operasi yang berhubungan dengan Timbunan Biner.

🕑

A complete binary tree can be stored efficiently as a compact array A as there is no gap between vertices of a complete binary tree/elements of a compact array. To simplify the navigation operations below, we use 1-based array. VisuAlgo displays the index of each vertex as a red label below each vertex. Read those indices in sorted order from 1 to N, then you will see the vertices of the complete binary tree from top to down, left to right. To help you understand this, Toggle the Visualization Mode several times.


This way, we can implement basic binary tree traversal operations with simple index manipulations (with help of bit shift manipulation):

  1. parent(i) = i>>1, index i divided by 2 (integer division),
  2. left(i) = i<<1, index i multiplied by 2,
  3. right(i) = (i<<1)+1, index i multiplied by 2 and added by 1.

Pro tip: Try opening two copies of VisuAlgo on two browser windows. Try to visualize the same Binary Max Heap in two different modes and compare them.

🕑

In this visualization, you can perform several Binary (Max) Heap operations:

  1. Create(A) - O(N log N) version (N calls of Insert(v) below)
  2. Create(A) - O(N) version
  3. Insert(v) in O(log N) — you are allowed to insert duplicates
  4. 3 versions of ExtractMax():
    1. Once, in O(log N)
    2. K times, i.e., PartialSort(), in O(K log N), or
    3. N times, i.e., HeapSort(), in O(N log N)
  5. UpdateKey(i, newv) in O(log N if i is known)
  6. Delete(i) in O(log N if i is known)

There are a few other possible Binary (Max) Heap operations, but currently we do not elaborate them for pedagogical reason in a certain NUS module.

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑
Masukkan(v): Memasukkan nilai baru v ke dalam Timbunan Biner Maks hanya dapat dilakukan pada indeks terakhir N plus 1 untuk mempertahankan properti larik padat = pohon biner komplet. Namun, properti Timbunan Maks masih dapat dilanggar. Operasi ini kemudian membetulkan properti tersebut dari titik masukkan ke atas (jika perlu) dan berhenti ketika properti tersebut tidak dilanggar lagi. Sekarang cobalah klik Insert(v) beberapa kali untuk memasukkan beberapa nilai v acak ke Timbunan Biner (Maks) yang ditunjukkan saat ini.

Operasi membetulkan properti Timbunan Maks keatas tidak memiliki nama standar. Kami menyebutnya ShiftUp tetapi orang-orang lain mungkin menyebutnya sebagai operasi BubbleUp atau IncreaseKey.
🕑

Apakah anda mengerti kenapa memulai dari tempat pemasukan (indeks N+1) keatas (sampai maksimum simpul akar) dan menukar sebuah simpul dangan orang tuanya ketika terjadi pelanggaran properti Timbunan Maks selama pemasukkan adalah sebuah strategi yang benar?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

Kompleksitas waktu dari operasi Masukkan(v) ini adalah O(log N).


Diskusi: Apakah anda mengerti penurunannya?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

EkstrakMaks(): Pelaporan dan penghapusan nilai maksimum (akar) dari Timbunan Biner Maks memerlukan sebuah elemen lain untuk menggantikannya, karena jika tidak, maka Timbunan Biner Maks (sebuah pohon biner komplit, atau 林/Lín dalam bahasa Mandarin/pohon) menjadi dua sub-pohon yang terpisah (dua kopi dari 木/mù dalam bahasa Mandarin/kayu). Elemen tersebut harus merupakan indeks terakhir N dengan alasan yang sama: Untuk menjaga properti larik padat (compact) = pohon biner komplet.


Karena kita mempromosikan sebuah simpul daun menjadi simpul akar dari sbeuah Timbunan Biner, properti Timbunan Maks dapat dilanggar dengan mudah. Operasi EkstraksMaks() ini lalu membetulkan kembali properti tersebut mulai dari akar ke bawah dengan membandingkan nilai saat ini dengan anak-anaknya/yang lebih besar (bila perlu). Sekarang cobalah ExtractMax() pada Timbunan Biner (Maks) yang ditunjukkan saat ini.


Operasi membetulkan properti Timbunan Maks kebawah tidak memiliki nama standar. Kami menyebutnya ShiftDown tetapi orang-orang lain mungkin menyebutnya sebagai operasi BubbleDown atau Heapify.

🕑

Kenapa jika sebuah simpul memiliki dua anak, kita harus mengecek (dan mungkin menukar) simpul tersebut dengan anak yang lebih besar saat membereskan properti Timbunan Maks kebawah?


Kenapa kita tidak bisa membandingkan dengan simpul kiri (atau kanan, jika ada) saja?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

Kompleksitas waktu dari operasi EkstrakMaks() ini adalah O(log N).


Diskusi: Apakah anda mengerti penurunannya?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

Up to here, we have a data structure that can implement the two major operations of Priority Queue (PQ) ADT efficiently:

  1. For Enqueue(x), we can use Insert(x) in O(log N) time, and
  2. For y = Dequeue(), we can use y = ExtractMax() in O(log N) time.

However, we can do a few more operations with Binary Heap.

🕑

Buat(A): Membuat sebuah Timbunan Biner (Maks) valid dari array masukan A dengan N integer (dipisahkan dengan koma) ke dalam Timbunan Biner Maks kosong.


Ada dua varian untuk operasi ini, versi sederhana dalam O(N log N) dan versi advanced yang berjalan dalam O(N).


Pro Tip: Cobalah buka dua jendela VisuAlgo di browser anda. Jalankan kedua varian operasi Buat(A) pada kasus terburuk 'Contoh terurut' untuk melihat perbedaan mencolok dari keduanya.

🕑

Create(A) - O(N log N): Simply insert (that is, by calling Insert(v) operation) all N integers of the input array into an initially empty Binary Max Heap one by one.


Analysis: This operation is clearly O(N log N) as we call O(log N) Insert(v) operation N times. Let's examine the 'Sorted example' which is one of the hard case of this operation (Now try the Hard Case - O(N log N) where we show a case where A = [1,2,3,4,5,6,7] -- please be patient as this example will take some time to complete). If we insert values in increasing order into an initially empty Binary Max Heap, then every insertion triggers a path from the insertion point (a new leaf) upwards to the root.

🕑

Create(A) - O(N): This faster version of Create(A) operation was invented by Robert W. Floyd in 1964. It takes advantage of the fact that a compact array = complete binary tree and all leaves (i.e., half of the vertices — see the next slide) are Binary Max Heap by default. This operation then fixes Binary Max Heap property (if necessary) only from the last internal vertex back to the root.


Analysis: A loose analysis gives another O(N/2 log N) = O(N log N) complexity but it is actually just O(2*N) = O(N) — details in the next few slides. Now try the Hard Case - O(N) on the same input array A = [1,2,3,4,5,6,7] and see that on the same hard case as with the previous slide (but not the one that generates maximum number of swaps — try 'Diagonal Entry' test case by yourself), this operation is far superior than the O(N log N) version.

🕑

Pembuktian sederhana tentang mengapa separuh dari Timbunan Biner (Maks) dengan N (tanpa kehilangan makna umum, mari asumsikan bahwa N adalah genap) elemen adalah dedaunan adalah sebagai berikut:


Misalkan daun terakhir berada pada indeks N, maka orang tua dari daun terakhir tersebut ada di indeks i = N/2 (ingat slide ini). Anak kiri dari simpul i+1, jika ada (sesungguhnya tidak ada), adalah 2*(i+1) = 2*(N/2+1) = N+2, yang sudah lebih besar dari indeks N (daun terakhir) jadi indeks i+1 pasti juga adalah sebuah simpul daun yang tidak mempunyai anak. Karena indeks-indeks dari Timbunan Biner beruruta, pada dasarnya indeks-indeks [i+1 = N/2+1, i+2 = N/2+2, ..., N], yaitu separuh dari seluruh simpul-simpul, adalah dedaunan.

🕑

Pertama-tama, kita perlu mengingat bahwa tinggi dari pohon biner penuh dengan ukuran N adalah log2 N.


Kedua, kita perlu menyadari bahwa biaya untuk menjalakan operasi shiftDown(i) tidak sejelek batas atas kasar O(log N), tetapi O(h) dimana h adalah tinggi dari sub-pohon yang berakar di indeks i.


Ketiga, ada ceil(N/2h+1) simpul-simpul pada ketinggian h di sebuah pohon biner penuh.


Di pohon biner penuh contoh diatas dengan N = 7 dan h = 2, ada:
ceil(7/20+1) = 4 simpul-simpul: {44,35,26,17} pada ketinggian h = 0,
ceil(7/21+1) = 2 simpul-simpul: {62,53} pada ketinggian h = 1, dan
ceil(7/22+1) = 1 simpul: {71} pada ketinggian h = 2.

🕑

Biaya dari Buat(A), versi O(N) adalah:


analysis

Catatan: Jika rumus ini terlalu kompleks, murid yang modern bisa menggunakan WolframAlpha.

🕑

HeapSort(): John William Joseph Williams meneukan algoritma HeapSort() pada tahun 1964, bersamaan dengan struktur data Timbunan Biner. Operasi HeapSort() (dengan asumsi bahwa Timbunan Biner Maks telah dibuat dalam O(N)) sangatlah mudah. Anda cukup memanggil operasi EkstrakMaks() yang berjalan dalam O(log N) sebanyak N kali. Sekarang cobalah HeapSort() pada Timbunan Biner (Maks) yang ditunjukkan saat ini.

Analisa Sederhana: HeapSort() dengan jelas berjalan dalam O(N log N) — sebuah algoritma pengurutan berbasis perbandingan yang optimal.

🕑

Meskipun HeapSort() berjalan dalam waktu θ(N log N) untuk semua kasus (terbaik/rata-rata/terjelek), apakah Heap Sort benar-benar algoritma berbasis-pembandingan terbaik?


Diskusi: Bagaimana dengan performa caching dari HeapSort()?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

We can actually just call the O(log N) ExtractMax() operation K times if we are only interested in the top K largest elements in the Binary (Max) Heap. Now try PartialSort() on the currently displayed Binary (Max) Heap. This operation is called PartialSort().


Simple Analysis: PartialSort() clearly runs in O(K log N) — an output-sensitive algorithm where the time complexity depends on the output size K.

🕑

Anda telah mencapai akhir dari bahan-bahan dasar dari struktur data Timbunan Biner (Maks) dan kami menyemangati anda untuk mengeksplorasi lebih lanjut dalam Mode Eksplorasi.


Tetapi, kami masih memiliki beberapa tantangan-tantangan menarik untuk anda tentang Timbunan Biner (Maks) yang akan kami sebutkan di bagian ini.


Ketika anda telah menyelesaikan semuanya, kami mengundang anda untuk mempelajari algoritma-algoritma yang lebih lanjut yang menggunakan Antrean Berprioritas sebagai (salah satu dari) struktur datanya, seperti algoritma MST Prim, algoritma SSSP Dijkstra, algoritma pencarian A* (belum ada di VisuAlgo), dan beberapa algoritma-algoritma berbasis-greedy lainnya, dsb.

🕑

Jika kita hanya berurusan dengan angka-angka (termasuk dalam visualisasi ini yang dibatasi nya untuk bilangan-bilangan bulat saja), maka mudah untuk mengkonversi Timbunan Biner Maks ke Timbunan Biner Min tanpa mengubah apapun, dan sebaliknya.


Kita dapat membuat ulang Timbunan Biner dengan menegasi (mengalikan dengan -1) setiap bilangan bulat di Timbunan Biner asli. Jika kita mulai dengan Timbunan Biner Maks, maka Timbunan Biner yang dihasilkan adalah Timbunan Biner Min (jika kita tidak memperdulikan simbol-simbol negatif — lihat gambar diatas), dan sebaliknya.

🕑

Untuk beberapa aplikasi-aplikasi Antrean Berprioritas (misalkan HeapDecreaseKey dalam algoritma Dijkstra), kita mungkin harus memodifikasi (menaikkan atau menurunkan) prioritas dari sebuah nilai yang sudah dimasukkan kedalam Timbunan Biner (Maks). Jika indeks i dari nilai tersebut diketahui, kita dapat menggunakan strategi mudah sebagai berikut: Mutakhirkan saja A[i] = newv dan lalu kita memanggil kedua shiftUp(i) dan shiftDown(i). Hanya maksimum satu dari operasi restorasi properti Timbunan Maks yang akan berhasil, yaitu shiftUp(i)/shiftDown(i) akan dijalankan jika newv >/< nilai lama dari A[parent(i)]/A[larger of the two children of i], masing-masing.


Sehingga, PerbaruiKunci(i, vbaru) bisa dilakukan dalam O(log N), asal saja kita mengetahui indeks i.

🕑

Untuk beberapa aplikasi-aplikasi Antrean Berprioritas, kita mungkin harus menghapus nilai yang sudah ada yang telah dimasukkan kedalam Timbunan Biner (Maks) (dan nilai ini kebetulan bukan akar). Sekali lagi, jika indeks i dari nilai tersebut diketahui, kita bisa melakukan strategi muda berikut ini: Mutakhirkan saja A[i] = A[1]+1 (sebuah angka besar yang lebih besar dari akar saat ini), panggil shiftUp(i) (secara teknis, PerbaruKunci(i, A[1]+1)). Ini akan membawa indeks i menjadi akar yang baru, dan dari situ, kita dapat dengan mudah memanggil EktraksMax() sekali untuk menghapusnya.


Maka, Hapus(i) bisa dilakukan dalam O(log N), jika kita mengetahui indeks i.


Diskusi: Sekarang untuk PerbaruiKunci(i, vbaru) dan Hapus(i), apa yang terjadi jika kita diberikan vlama dan oleh karena itu kita harus mencari lokasinya di Timbunan Biner (Maks)? Bisakah kita melakukan ini lebih cepat dari O(N)?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

If you are looking for an implementation of Binary (Max) Heap to actually model a Priority Queue, then there is a good news.


C++ and Java already have built-in Priority Queue implementations that very likely use this data structure. They are C++ STL priority_queue (the default is a Max Priority Queue) and Java PriorityQueue (the default is a Min Priority Queue). However, the built-in implementation may not be suitable to do some PQ extended operations efficiently (details omitted for pedagogical reason in a certain NUS course).


Python heapq exists but its performance is rather slow. OCaml doesn't have built-in Priority Queue but we can use something else that is going to be mentioned in the other modules in VisuAlgo (the reason on why the details are omitted is the same as above).


PS: Heap Sort is likely used in C++ STL algorithm partial_sort.


Nevertheless, here is our implementation of BinaryHeapDemo.cpp | py | java.

🕑

Untuk beberapa pertanyaan-pertanyaan menarik tentang struktur data ini, silahkan coba latihan pada modul latihan Timbunan Biner (login tidak dibutuhkan).


Tetapi untuk murid-murid NUS, anda sebaiknya login menggunakan akun kelas resmi anda, secara ofisial menyelesaikan modul ini, dan penghargaan tersebut akan dicatat di akun pengguna anda.

🕑

Kita juga memiliki beberapa masalah-masalah pemrograman yang membutuhkan penggunaan struktur data Timbunan Biner ini: UVa 01203 - Argus dan Kattis - numbertree.


Cobalah mereka untuk mengkonsolidasikan dan meningkatkan pemahaman anda tentang struktur data ini. Anda diijinkan untuk menggunakan C++ STL priority_queue, Python heapq, atau Java PriorityQueue jika itu mempermudah implementasi anda.

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.

🕑

Setelah menghabiskan satu kuliah panjang tentang Timbunan Biner (Maks), pernyataan berikutnya bisa mengejutkan anda...


Timbunan Biner (Maks) mungkin bukan struktur data terbaik untuk mengimplementasikan (beberapa operasi-operasi spesifik) dari ADT Antrian Berprioritas...


Diskusi: Jadi apakah data struktur alternatifnya?

🕑

The content of this interesting slide (the answer of the usually intriguing discussion point from the earlier slide) is hidden and only available for legitimate CS lecturer worldwide. This mechanism is used in the various flipped classrooms in NUS.


If you are really a CS lecturer (or an IT teacher) (outside of NUS) and are interested to know the answers, please drop an email to stevenhalim at gmail dot com (show your University staff profile/relevant proof to Steven) for Steven to manually activate this CS lecturer-only feature for you.


FAQ: This feature will NOT be given to anyone else who is not a CS lecturer.


You have reached the last slide. Return to 'Exploration Mode' to start exploring!

Note that if you notice any bug in this visualization or if you want to request for a new visualization feature, do not hesitate to drop an email to the project leader: Dr Steven Halim via his email address: stevenhalim at gmail dot com.

🕑

-> Mode Larik Kompak

Buat(A) - O(N log N)

Buat(A) - O(N)

Masukkan(v)

ExtractMax()

UpdateKey(i, newv)

Delete(i)

>
A =

Lakukan

Kasus Terbaik: Urutkan Menurun

N =

Acak

Worst Case: Sorted Ascending

A =

Lakukan

Kasus Terbaik: Urutkan Menurun

N =

Acak

Worst Case: Diagonal Entry

v =

Lakukan

1x (Sekali)

K =

Kx (UrutkanSebagian)

Nx (HeapSort)

i =
newv =

Lakukan

i =

Lakukan

Tentang Tim Syarat Guna Kebijakan Privasi

Tentang

Initially conceived in 2011 by Associate Professor Steven Halim, VisuAlgo aimed to facilitate a deeper understanding of data structures and algorithms for his students by providing a self-paced, interactive learning platform.

Featuring numerous advanced algorithms discussed in Dr. Steven Halim's book, 'Competitive Programming' — co-authored with Dr. Felix Halim and Dr. Suhendry Effendy — VisuAlgo remains the exclusive platform for visualizing and animating several of these complex algorithms even after a decade.

While primarily designed for National University of Singapore (NUS) students enrolled in various data structure and algorithm courses (e.g., CS1010/equivalent, CS2040/equivalent (including IT5003), CS3230, CS3233, and CS4234), VisuAlgo also serves as a valuable resource for inquisitive minds worldwide, promoting online learning.

Initially, VisuAlgo was not designed for small touch screens like smartphones, as intricate algorithm visualizations required substantial pixel space and click-and-drag interactions. For an optimal user experience, a minimum screen resolution of 1366x768 is recommended. However, since April 2022, a mobile (lite) version of VisuAlgo has been made available, making it possible to use a subset of VisuAlgo features on smartphone screens.

VisuAlgo remains a work in progress, with the ongoing development of more complex visualizations. At present, the platform features 24 visualization modules.

Equipped with a built-in question generator and answer verifier, VisuAlgo's "online quiz system" enables students to test their knowledge of basic data structures and algorithms. Questions are randomly generated based on specific rules, and students' answers are automatically graded upon submission to our grading server. As more CS instructors adopt this online quiz system worldwide, it could effectively eliminate manual basic data structure and algorithm questions from standard Computer Science exams in many universities. By assigning a small (but non-zero) weight to passing the online quiz, CS instructors can significantly enhance their students' mastery of these basic concepts, as they have access to an almost unlimited number of practice questions that can be instantly verified before taking the online quiz. Each VisuAlgo visualization module now includes its own online quiz component.

VisuAlgo has been translated into three primary languages: English, Chinese, and Indonesian. Additionally, we have authored public notes about VisuAlgo in various languages, including Indonesian, Korean, Vietnamese, and Thai:

id, kr, vn, th.

Tim

Pemimpin & Penasihat Proyek (Jul 2011-sekarang)
Associate Professor Steven Halim, School of Computing (SoC), National University of Singapore (NUS)
Dr Felix Halim, Senior Software Engineer, Google (Mountain View)

Murid-Murid S1 Peniliti 1
CDTL TEG 1: Jul 2011-Apr 2012: Koh Zi Chun, Victor Loh Bo Huai

Murid-Murid Proyek Tahun Terakhir/UROP 1
Jul 2012-Dec 2013: Phan Thi Quynh Trang, Peter Phandi, Albert Millardo Tjindradinata, Nguyen Hoang Duy
Jun 2013-Apr 2014 Rose Marie Tan Zhao Yun, Ivan Reinaldo

Murid-Murid S1 Peniliti 2
CDTL TEG 2: May 2014-Jul 2014: Jonathan Irvin Gunawan, Nathan Azaria, Ian Leow Tze Wei, Nguyen Viet Dung, Nguyen Khac Tung, Steven Kester Yuwono, Cao Shengze, Mohan Jishnu

Murid-Murid Proyek Tahun Terakhir/UROP 2
Jun 2014-Apr 2015: Erin Teo Yi Ling, Wang Zi
Jun 2016-Dec 2017: Truong Ngoc Khanh, John Kevin Tjahjadi, Gabriella Michelle, Muhammad Rais Fathin Mudzakir
Aug 2021-Apr 2023: Liu Guangyuan, Manas Vegi, Sha Long, Vuong Hoang Long, Ting Xiao, Lim Dewen Aloysius

Murid-Murid S1 Peniliti 3
Optiver: Aug 2023-Oct 2023: Bui Hong Duc, Oleh Naver, Tay Ngan Lin

Murid-Murid Proyek Tahun Terakhir/UROP 3
Aug 2023-Apr 2024: Xiong Jingya, Radian Krisno, Ng Wee Han

List of translators who have contributed ≥ 100 translations can be found at statistics page.

Ucapan Terima Kasih
NUS CDTL gave Teaching Enhancement Grant to kickstart this project.

For Academic Year 2023/24, a generous donation from Optiver will be used to further develop VisuAlgo.

Syarat Guna

VisuAlgo is generously offered at no cost to the global Computer Science community. If you appreciate VisuAlgo, we kindly request that you spread the word about its existence to fellow Computer Science students and instructors. You can share VisuAlgo through social media platforms (e.g., Facebook, YouTube, Instagram, TikTok, Twitter, etc), course webpages, blog reviews, emails, and more.

Data Structures and Algorithms (DSA) students and instructors are welcome to use this website directly for their classes. If you capture screenshots or videos from this site, feel free to use them elsewhere, provided that you cite the URL of this website (https://visualgo.net) and/or the list of publications below as references. However, please refrain from downloading VisuAlgo's client-side files and hosting them on your website, as this constitutes plagiarism. At this time, we do not permit others to fork this project or create VisuAlgo variants. Personal use of an offline copy of the client-side VisuAlgo is acceptable.

Please note that VisuAlgo's online quiz component has a substantial server-side element, and it is not easy to save server-side scripts and databases locally. Currently, the general public can access the online quiz system only through the 'training mode.' The 'test mode' offers a more controlled environment for using randomly generated questions and automatic verification in real examinations at NUS.

List of Publications

This work has been presented at the CLI Workshop at the ICPC World Finals 2012 (Poland, Warsaw) and at the IOI Conference at IOI 2012 (Sirmione-Montichiari, Italy). You can click this link to read our 2012 paper about this system (it was not yet called VisuAlgo back in 2012) and this link for the short update in 2015 (to link VisuAlgo name with the previous project).

Bug Reports or Request for New Features

VisuAlgo is not a finished project. Associate Professor Steven Halim is still actively improving VisuAlgo. If you are using VisuAlgo and spot a bug in any of our visualization page/online quiz tool or if you want to request for new features, please contact Associate Professor Steven Halim. His contact is the concatenation of his name and add gmail dot com.

Kebijakan Privasi

Version 1.2 (Updated Fri, 18 Aug 2023).

Since Fri, 18 Aug 2023, we no longer use Google Analytics. Thus, all cookies that we use now are solely for the operations of this website. The annoying cookie-consent popup is now turned off even for first-time visitors.

Since Fri, 07 Jun 2023, thanks to a generous donation by Optiver, anyone in the world can self-create a VisuAlgo account to store a few customization settings (e.g., layout mode, default language, playback speed, etc).

Additionally, for NUS students, by using a VisuAlgo account (a tuple of NUS official email address, student name as in the class roster, and a password that is encrypted on the server side — no other personal data is stored), you are giving a consent for your course lecturer to keep track of your e-lecture slides reading and online quiz training progresses that is needed to run the course smoothly. Your VisuAlgo account will also be needed for taking NUS official VisuAlgo Online Quizzes and thus passing your account credentials to another person to do the Online Quiz on your behalf constitutes an academic offense. Your user account will be purged after the conclusion of the course unless you choose to keep your account (OPT-IN). Access to the full VisuAlgo database (with encrypted passwords) is limited to Prof Halim himself.

For other CS lecturers worldwide who have written to Steven, a VisuAlgo account (your (non-NUS) email address, you can use any display name, and encrypted password) is needed to distinguish your online credential versus the rest of the world. Your account will have CS lecturer specific features, namely the ability to see the hidden slides that contain (interesting) answers to the questions presented in the preceding slides before the hidden slides. You can also access Hard setting of the VisuAlgo Online Quizzes. You can freely use the material to enhance your data structures and algorithm classes. Note that there can be other CS lecturer specific features in the future.

For anyone with VisuAlgo account, you can remove your own account by yourself should you wish to no longer be associated with VisuAlgo tool.