Skip to main content

C Program To Implement Heap Sort Algorithm.

Heap Sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios. The algorithm can be divided into 2 basic parts:

[1] Creating a Heap of the unsorted list. [2] Then a sorted array is created by repeatedly removing the largest/smallest element from the heap, and inserting it into the array. The heap is reconstructed after each removal.

Heap is a tree-based data structure that satisfies two special properties: 
*** Heap data structure is always a Complete Binary Tree, which means all levels of the tree are fully filled.


*** All nodes are either [greater than or equal to] or [less than or equal to] each of its children. If the parent nodes are greater than their children, heap is called a Max-Heap, and if the parent nodes are smaller than their child nodes, heap is called Min-Heap.


How Heap Sort Works: Initially on receiving an unsorted list, the first step is to create a Heap data structure (Max-Heap or Min-Heap). Once heap is built, the first element of the Heap is either largest or smallest (based on Max-Heap or Min-Heap), now we can put the first element of the heap in the array. Then we again make heap using the remaining elements, to again pick the first element of the heap and put it into the array. We keep on doing the same repeatedly until we have the complete sorted list in the array.

Let { 80, 32, 31, 110, 50, 40, 120 } be the list that we want to sort from the smallest to the largest (Max-heap).

Now all elements are sorted: 31, 32, 40, 50, 80, 110, 120.

Source Code - Method 01:
#include <stdio.h>
#include <stdlib.h>

#define ValType double
#define IS_LESS(v1, v2)  (v1 < v2) 
// To sort in descending order, change < to > only.

#define SWAP(r,s)  do{ValType t=r; r=s; s=t; } while(0)

void siftDown( ValType *a, int start, int count);
void heapsort( ValType *a, int count) {
int start, end;

for (start = (count-2)/2; start >=0; start--) {
siftDown( a, start, count);
}

for (end=count-1; end > 0; end--) {
SWAP(a[end],a[0]);
siftDown(a, 0, end);
}}

void siftDown( ValType *a, int start, int end) {
int root = start;

while ( root*2+1 < end ) {
int child = 2*root + 1;

if ((child + 1 < end) && IS_LESS(a[child],a[child+1])) {
child += 1;
}

if (IS_LESS(a[root], a[child])) {
SWAP( a[child], a[root] );
root = child;
}
else
return;
}}

int main() {
int n;

double valsToSort[] = {1.3, 50.9, 15.22, -1.77, 301.501, 0.3301, 40.17, 30.54, -37.2, 49.6};

#define VSIZE (sizeof(valsToSort)/sizeof(valsToSort[0]))
heapsort(valsToSort, VSIZE);

for (n=0; n<VSIZE; n++) printf("( %.3f )\n\n", valsToSort[n]);
return 0;
}

Source Code - Method 02:
#include<stdio.h>

void heapsort(int[],int);
void heapify(int[],int);
void adjust(int[],int);

main() {
int n,i,a[50];

printf("\nEnter How Many Number You Want To Sort : ");
scanf("%d",&n);

printf("\nEnter %d Numbers: \n", n);

for (i=0;i<n;i++)
scanf("%d",&a[i]);

heapsort(a,n);

printf("\nThe Sorted Numbers Are: ");

for (i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
}

void heapsort(int a[],int n) {
int i,t;
heapify(a,n);

for (i=n-1;i>0;i--) {
t = a[0];
a[0] = a[i];
a[i] = t;

adjust(a,i);
}}

void heapify(int a[],int n) {
int k,i,j,item;

for (k=1;k<n;k++)
{
item = a[k];
i = k;
j = (i-1)/2;

while((i>0)&&(item>a[j]))  // To sort in descending order, change item > a[j] to item < a[j]
{
a[i] = a[j];
i = j;
j = (i-1)/2;
}

a[i] = item;
}}

void adjust(int a[],int n) {
int i,j,item;

j = 0;
item = a[j];
i = 2*j+1;

while(i<=n-1)
{
if(i+1 <= n-1) 
if(a[i] <a[i+1])
i++;

if(item<a[i])
{
a[j] = a[i];
j = i;
i = 2*j+1;
}
else break;
}
a[j] = item;
}

Source Code - Method 03:
#include <stdio.h>
#include <stdlib.h>

struct MaxHeap {
int size;
int* array;
};

void swap(int* a, int* b) { int t = *a; *a = *b;  *b = t; }
void maxHeapify(struct MaxHeap* maxHeap, int idx)
{
int largest = idx;
int left = (idx << 1) + 1;
int right = (idx + 1) << 1;

if (left < maxHeap->size
&& maxHeap->array[left] > maxHeap->array[largest]) largest = left;
//for arranging numbers in descending order, change to maxHeap-> array[left] < maxHeap->array[largest]

if (right < maxHeap->size
&& maxHeap->array[right] > maxHeap->array[largest]) largest = right;
//for arranging numbers in descending order, change to maxHeap-> array[right] < maxHeap->array[largest]

if (largest != idx) {
swap(&maxHeap->array[largest], &maxHeap->array[idx]);
maxHeapify(maxHeap, largest);
}}

struct MaxHeap* createAndBuildHeap(int *array, int size)
{
int i;
struct MaxHeap* maxHeap = (struct MaxHeap*) malloc(sizeof(struct MaxHeap));

maxHeap->size = size;  
maxHeap->array = array;

for (i = (maxHeap->size - 2) / 2; i >= 0; --i)
maxHeapify(maxHeap, i);
return maxHeap;
}

void heapSort(int* array, int size) {
struct MaxHeap* maxHeap = createAndBuildHeap(array, size);

while (maxHeap->size > 1) {
swap(&maxHeap->array[0], &maxHeap->array[maxHeap->size - 1]);

--maxHeap->size;
maxHeapify(maxHeap, 0);
}}

void printArray(int* arr, int size) {
int i;

for (i = 0; i < size; ++i)
printf("%d ", arr[i]);
}

int main() {
int arr[] = {74,12,15,10,5,17,9,35,6};
int size = sizeof(arr)/sizeof(arr[0]);

printf(" The Unsorted Numbers Are: ");
printArray(arr, size);

heapSort(arr, size);

printf("\n\n After Sorting Them In Ascending Order: "); 
printArray(arr, size);

printf("\n");
return 0;

Popular posts from this blog

Screenshots from Windows 1.01

Windows 1.0 is a graphical personal computer operating environment developed by Microsoft, released on November 20, 1985, as the first version of the Microsoft Windows line. Version 1.01 , also released in 1985, was the first point-release after Windows 1.00.   Screenshots from Windows 1.01: ⇰ Desktop  First Run Empty Desktop Desktop With Applications ⇰  Office Applications Notepad Text Editor Calculator Calendar Clock Address Book ⇰  Multimedia Applications Media player, CD player, Volume level, and Sound: This GUI doesn’t have these features. ⇰  Networking Applications Terminal Phone Dialer: This GUI doesn’t have this feature. ⇰  Internet Applications Browser, and Mail: This GUI doesn’t have these features. ⇰  Accessibility Applications Keyboard Map:  This GUI doesn’t have this feature. ⇰  Settings Desktop themes,  Display,  S...

The C Programming Language, 2nd Edition*

This book is meant to help the reader learn how to program in C. It is the definitive reference guide, now in a second edition. Although the first edition was written in 1978, it continues to be a worldwide best-seller. This second edition brings the classic original up to date to include the ANSI standard. For evolution of the planet earth and our modern understanding of biology, there was Darwin's Origin of the Species. For mathematics, there was Newton's PhilosophiƦ Naturalis Principia Mathematica. Well, for the internet, for Facebook, for LinkedIn, Twitter, Instgram, Snapchat, WhatsApp, Pornhub and even the odious website for Justin Bieber would never have existed without Kernigan and Ritchie (more affectionately known as K&R)'s classic, The C Programming Language. What language was TCP/IP written in? C. What language inspired both C++ and Java (and the abominable C#)? C. What language are most libraries on most operating systems written in if not assembler? C. ...

C++ Program To Implement Casino Number Guessing Game.

#include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; void drawLine(int n, char symbol); void rules(); int main() { string playerName; int amount; int bettingAmount; int guess; int dice; char choice; srand(time(0)); drawLine(70,'_'); cout << "\n\n\n\t\tCASINO GAME\n\n\n\n"; drawLine(70,'_'); cout << "\n\nEnter Your Name : "; getline(cin, playerName); cout << "\n\nEnter Deposit Amount To Play Game : $"; cin >> amount;

Java: The Complete Reference, 9th Edition

This is Herb's most popular book on Java, fully updated and expanded to cover Java SE 8 (JDK 8).    Whether you're an experienced pro or just starting out, this one-stop guide will help you master this important language.  Inside you'll find comprehensive coverage of the Java language, its keywords, syntax, and fundamental programming principles.  Of course, descriptions of Java's newest features, such as lambda expressions, default interface methods, and the stream API are included. This lasting resource also describes key elements of the Java API library, such as the Collections Framework, concurrency, applets, servlets, Beans, event handling,  AWT,  Swing, and more. Coverage of JavaFX, Java's newest GUI framework, is also included. *** TO REVIEW BOOK ***  (click below) *** TO REVIEW SOURCE CODE PROBLEM  SOLUTIONS, VISIT   THIS   LINK ***

Java: A Beginner's Guide, 6th Edition

This is Herb's step-by-step introduction to Java, updated for Java SE 8 (JDK 8). If you are just learning Java, then this is the book for you.  It starts at the beginning, explaining the history of Java, why it's important to the Web, and how it relates to the world of programming at large.  You then learn how to obtain the Java Development Kit (JDK) and write your first Java program. Next, it's on to the Java fundamentals, including data types, operators, control statements, classes, objects, and methods.  You'll then progress to more advanced topics, such as inheritance, exception handling, the I/O system, multithreading,  applets, and lambda expressions. Also included is coverage of some of Java's most powerful features, such as generics, autoboxing, enumerations, and static import.  An introduction to JavaFX, Java's newest GUI framework, is also included. *** TO REVIEW BOOK *** (click below) *** TO REVIEW SOURCE CODE PROBLEM  SO...