Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update heapsort.c #450

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions heapsort.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@ void main()
{
int heap[10], no, i, j, c, root, temp;

printf("\n Enter no of elements :");
scanf("%d", &no);
printf("\nEnter number of elements (max 10): ");
scanf("%d", &no);
if (no > 10)
{
printf("Number of elements exceeds the maximum limit of 10.\n");
return 1; // Exit if the number of elements exceeds the limit
}
printf("\n Enter the nos : ");
for (i = 0; i < no; i++)
scanf("%d", &heap[i]);
Expand Down Expand Up @@ -37,9 +42,17 @@ void main()
do
{
c = 2 * root + 1; /* left node of root element */
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[root]<heap[c] && c<j) /* again rearrange to max heap array */
if (c < j)
{ // Check if left child is within bounds
if (c + 1 < j && heap[c] < heap[c + 1]) // Check if right child exists and is greater
c++; // Move to the right child
if (heap[root] < heap[c]) { // Swap if root is less than the largest child
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
root = c; // Move down to the child
}
{
temp = heap[root];
heap[root] = heap[c];
Expand All @@ -48,8 +61,8 @@ void main()
root = c;
} while (c < j);
}
printf("\n The sorted array is : ");
printf("\n The sorted array is: ");
for (i = 0; i < no; i++)
printf("\t %d", heap[i]);
printf("\n Complexity : \n Best case = Avg case = Worst case = O(n logn) \n");
}
}