0
0
DSA Goprogramming~30 mins

Heap Insert Operation Bubble Up in DSA Go - Build from Scratch

Choose your learning style9 modes available
Heap Insert Operation Bubble Up
📖 Scenario: You are managing a priority queue for tasks using a min-heap. Each task has a priority number, and lower numbers mean higher priority.When you add a new task, you must place it correctly in the heap so the smallest priority is always at the top.
🎯 Goal: Build a min-heap insert operation that adds a new priority number and moves it up (bubble up) to keep the heap order.
📋 What You'll Learn
Create a slice called heap with initial values representing a min-heap
Create a variable called newPriority with the new task's priority number
Write a bubble up loop to insert newPriority into heap and maintain min-heap order
Print the final heap slice after insertion
💡 Why This Matters
🌍 Real World
Priority queues are used in task scheduling, network packet management, and event simulation where tasks with higher priority must be handled first.
💼 Career
Understanding heap insertions and bubble up operations is essential for roles in software development, especially in systems programming, backend services, and algorithm design.
Progress0 / 4 steps
1
Create initial min-heap slice
Create a slice called heap with these exact integer values: 2, 5, 8, 10, 15.
DSA Go
Hint

Use heap := []int{2, 5, 8, 10, 15} to create the slice.

2
Add new priority value
Create an integer variable called newPriority and set it to 4.
DSA Go
Hint

Use newPriority := 4 to create the variable.

3
Insert and bubble up new priority
Append newPriority to heap. Then use a for loop with variable index starting at the last element's index. Inside the loop, calculate parentIndex as (index - 1) / 2. While index > 0 and heap[index] < heap[parentIndex], swap heap[index] and heap[parentIndex], then update index = parentIndex. This will bubble up the new priority to maintain the min-heap property.
DSA Go
Hint

Remember to append first, then bubble up by swapping with parent while smaller.

4
Print the final heap slice
Write fmt.Println(heap) to print the heap slice after insertion and bubbling up.
DSA Go
Hint

Use fmt.Println(heap) to show the final heap.