Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why is the int i in the first for loop in the heapsort start at (n/2-1)? Why not 0?
Geeksforgeeks heapsort

What I have tried:

Geeksforgeeks
Facebook
Stack overflow
Posted
Updated 22-Mar-20 21:19pm

1 solution

Think about it.
n is the number of elements in the collection to be sorted.
So what is (n / 2 - 1)?
Simple: it's a the midpoint of the collection, and the last node that could possibly have children, using i = 1 ... n inclusive rather than 0 ... n - 1 inclusive for the indexes. All the nodes from n / 2 + 1 to n are leaves.

Heap algorithms tend to use 1 ... n notation because it makes the calculation of child node indices cleaner. When using this notation the children of node x are at 2x and 2x + 1, and the parent of x is at x / 2. If you use 0 ... (n - 1) then the children of node x are at 2x + 1 and 2x + 2, and the parent of node x is at (x - 1) / 2.
 
Share this answer
 
Comments
CPallini 23-Mar-20 4:10am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900