let mut heap = vec![20, 18, 10, 12, 9]; heap.push(15); // Bubble up operation starts here let mut idx = heap.len() - 1; while idx > 0 { let parent = (idx - 1) / 2; if heap[idx] > heap[parent] { heap.swap(idx, parent); idx = parent; } else { break; } } println!("{:?}", heap);
After inserting 15 at the end, the array is [20, 18, 10, 12, 9, 15]. Bubble up compares 15 with its parent 10 and swaps them. The array becomes [20, 18, 15, 12, 9, 10]. Since 15 is now less than its new parent 18, bubbling stops.
let mut heap = vec![30, 20, 15, 10, 8, 12]; heap.push(25); let mut idx = heap.len() - 1; while idx > 0 { let parent = (idx - 1) / 2; if heap[idx] > heap[parent] { heap.swap(idx, parent); idx = parent; } else { break; } } println!("{:?}", heap);
Insert 25 at the end: [30, 20, 15, 10, 8, 12, 25]. Compare 25 with parent 15, swap: [30, 20, 25, 10, 8, 12, 15]. Then compare 25 with new parent 20, swap: [30, 25, 20, 10, 8, 12, 15]. 25 is less than 30, so stop.
let mut heap = vec![40, 30, 20, 15, 10]; heap.push(35); let mut idx = heap.len() - 1; while idx > 0 { let parent = idx / 2; if heap[idx] > heap[parent] { heap.swap(idx, parent); idx = parent; } else { break; } } println!("{:?}", heap);
The parent index is calculated as idx / 2, which is incorrect for zero-based arrays. For idx=1, parent=0 is correct, but for idx=2, parent=1 is correct. However, for idx=0, parent=0, but the loop stops at idx>0. The main problem is that for idx=1, parent=0, but for idx=5 (last element), parent=2 which is valid. However, the calculation is off by one compared to (idx - 1) / 2. This can cause incorrect parent indexing and potentially out of bounds access.
let mut heap = vec![50, 30, 40, 10, 20]; heap.push(5); let mut idx = heap.len() - 1; while idx > 0 { let parent = (idx - 1) / 2; if heap[idx] > heap[parent] { heap.swap(idx, parent); idx = parent; } else { break; } } println!("{:?}", heap);
After inserting 5 at the end, the array is [50, 30, 40, 10, 20, 5]. Bubble up compares 5 with its parent 40. Since 5 is less, no swap occurs and bubbling stops immediately.
let mut heap = Vec::new(); for &val in &[10, 20, 5, 30, 25] { heap.push(val); let mut idx = heap.len() - 1; while idx > 0 { let parent = (idx - 1) / 2; if heap[idx] > heap[parent] { heap.swap(idx, parent); idx = parent; } else { break; } } } println!("{:?}", heap);
Insert 10: [10]
Insert 20: [20, 10] (20 bubbles up)
Insert 5: [20, 10, 5]
Insert 30: [30, 20, 5, 10] (30 bubbles up to root)
Insert 25: [30, 25, 5, 10, 20] (25 bubbles up swapping with 10 and then 20)
Final heap array is [30, 25, 20, 10, 5].
