Choonz325
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Week 11 - Heaps ## Team Team name: Academy Award Winning, Choccy Milk Drinking, Argonian Maid Reading, Chair-men, Cross Dressing SIMPS In Yugoslavia With Honda Accords On The Quest For Feet Date: 23/05/2022 yes(66%) Members Mihnea: Mihnea Bastea (514541) Vlad: Vladislav Serafimov (509761) Steve: Stephen Cruz Wright (521476) | Role | Name | | ------------------------------------------------------------------------------------------------------------------------------------- | ------ | | **Facilitator** keeps track of time, assigns tasks and makes sure all the group members are heard and that decisions are agreed upon. | Steve | | **Spokesperson** communicates group’s questions and problems to the teacher and talks to other teams; presents the group’s findings. | Mihnea | | **Recorder** guides consensus building in the group by recording answers to questions. Collects important information and data. | Vlad | ## Activities Make sure to have the activities signed off regularly to ensure progress is tracked. Download the provided project and open it in CLion. **NOTE**: in this week you will have to reuse the code of last week. Follow the instructions given in the `main.cpp` file. ### Activity 1: Comparing different data structures | Data structure | Find-max | Delete-Max | Insert | | ------------------ |:---------:|:----------:| --------- | | Sorted array | O(log(n) | O(n) | O(1) | | Sorted linked list | O(n) | O(1) | O(1) | | Balanced BST | O(log(n)) | O(log(n)) | O(log(n)) | ### Activity 2: Identify valid heaps The left tree is a min-heap. The middle tree is not a heap because 29 is smaller than both 37 and 31, makin it not the maximum. the right tree is a min-heap. ### Activity 3: Do it yourself Swapped 12 and 3. Swapped 12 and 11. so just 2 swaps ### Activity 4: Worst-case time complexities | Data structure | Find-max | Delete-Max | Insert | Find | | --------------- |:--------:|:----------:|:---------:|:---------:| | Balanced BST | O(n) | O(n) | O(log(n)) | O(log(n)) | | Binary max-heap | O(1) | O(log(n)) | O(n) | O(n) | ### Activity 5: Index computations ```c++ size_t maxheap::parent_index(size_t index) { // Activity 5 auto idx = (index - 1) / 2; if (index == 0) return npos; else return idx; } size_t maxheap::left_child_index(size_t index) { // Activity 5 auto idx = 2 * index + 1; if (m_values[idx].priority == 0) return npos; else return idx; } size_t maxheap::right_child_index(size_t index) { // Activity 5 auto idx = 2 * index + 2; if (m_values[idx].priority == 0) return npos; else return idx; } ``` ### Activity 6: Implement the find-max operation ```c++ const task &maxheap::maximum() const { // Activity 6 return m_values[0]; } ``` ### Activity 7: Bubbling up ```c++ size_t maxheap::bubble_up(size_t index) { // Activity 7 // while the value at the given index is greater than its parent value, // bubble it up // use the functions swap and parent_index int Count = 0; while (index > 0 && m_values[parent_index(index)].priority <= m_values[index].priority) { swap(parent_index(index), index); index = parent_index(index); ++Count; } return Count; } ``` ### Activity 8: Bubbling down ```c++ size_t maxheap::bubble_down(size_t index) { // Activity 8 // While the value at the given index is smaller than any of its two child m_values, // bubble it down // use the functions swap, left_child_index, and right_child_index int Count = 0; size_t child = left_child_index(index); while (child < size()) { if (right_child_index(index) < size() && m_values[right_child_index(index)].priority > m_values[left_child_index(index)].priority) child++; if (m_values[child].priority <= m_values[index].priority) return Count; swap(child, index); index = child; child = left_child_index(index); ++Count; } return Count; } ``` ### Activity 9: Implement heapify ```c++ size_t maxheap::heapify() { // Activity 9 // fix heap violations by bubbling m_values down, starting with leaf nodes size_t swaps = 0; for (auto i = size(); i > 1; --i) { swaps+=bubble_down((i-1)/2); } return swaps; } ``` ### Activity 10: Heapify - time complexity | Number of values | Number of swaps | | ---------------- |:---------------:| | 5 | 3 | | 10 | 8 | | 20 | 17 | | 50 | 47 | | 100 | 96 | | 200 | 195 | | 300 | 295 | | 400 | 394 | | 500 | 493 | | 1000 | 992 | it is O(n) as it need to swap about the same times as the number of values ### Activity 11: Bubbling down vector elements ```c++ void bubble_down(std::vector<int> &values, size_t index, size_t count) { auto child = 2 * index + 1; while (child < count) { if (child + 1 < count && values[child + 1] > values[child]) child++; if (values[child] <= values[index]) return; std::swap(values[child], values[index]); index = child; child = 2 * index + 1; } } void heapify(std::vector<int> &numbers){ for (auto i = numbers.size(); i > 1; --i) { bubble_down(numbers,(i-1)/2 , numbers.size()); } } ``` ### Activity 12: In-place heap sort ```c++ void heap_sort(std::vector<int> &numbers) { heapify(numbers); auto count = numbers.size(); while (count-- > 1) { std::swap(numbers[count], numbers[0]); bubble_down(numbers, 0, count); } } ``` ### Activity 13: General heap sort ```c++ template<typename T> void bubble_down(std::vector<T> &values, size_t index, size_t count) { auto child = 2 * index + 1; while (child < count) { if (child + 1 < count && values[child + 1] > values[child]) child++; if (values[child] <= values[index]) return; std::swap(values[child], values[index]); index = child; child = 2 * index + 1; } } template<typename T> void heapify(std::vector<T> &numbers) { for (auto i = numbers.size(); i > 1; --i) { bubble_down(numbers, (i - 1) / 2, numbers.size()); } } template<typename T> void heap_sort(std::vector<T> &numbers) { heapify(numbers); auto count = numbers.size(); while (count-- > 1) { std::swap(numbers[count], numbers[0]); bubble_down(numbers, 0, count); } } ``` The program ran without any errors ## Looking back ### What we've learnt The ins and outs of heaps as well as the fact that theyre only really useful for quickly finding the max or min values. ### What were the surprises how difficult it was to implement binary heaps ### What problems we've encountered Converting the visualisation of the heaps to code ### What was or still is unclear nothing ### How did the group perform? well

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully