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...

Introduction To Algorithms, 3rd Edition

Before there were computers, there were algorithms. But now that there are computers, there are even more algorithms, and algorithms lie at the heart of computing. This book provides a comprehensive introduction to the modern study of computer algorithms. It presents many algorithms and covers them in considerable depth, yet makes their design and analysis accessible to all levels of readers. In this book, the authors tried to keep explanations elementary without sacrificing depth of coverage or mathematical rigor. Each chapter presents an algorithm, a design technique, an application area, or a related topic. Algorithms are described in English and in a pseudocode designed to be readable by anyone who has done a little programming. The book contains 244 figures — many with multiple parts — illustrating how the algorithms work. It also includes careful analysis of the running times of all algorithms. In this third edition, the entire book once again updated including changes cove...

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 ***