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

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 Check Whether A Number Is Palindrome Or Not.

This program takes an integer from user and the integer is reversed. If the reversed integer is equal to the integer entered by user then that number is a palindrome. If not that number is not a palindrome.   #include <stdio.h> int main()  { int num, temp, remainder, reverse = 0; printf("Enter an integer: "); scanf("%d", &num); /*  original number is stored at temp */ temp = num; while (num > 0)  { remainder = num % 10; reverse = reverse * 10 + remainder; num /= 10;   }

The Basics Of C Programming - Part 3.

There are a number of different C input commands, the most useful of which is the scanf command. To read a single integer value into the variable called a you can use: scanf("%d",&a); When the program reaches the scanf statement it pauses to give the user time to type something on the keyboard and continues only when users press Enter or Return, to signal that he, or she, has finished entering the value. Then the program continues with the new value stored in a. In this way, each time the program is run the user gets a chance to type in a different value to the variable and the program also gets the chance to produce a different result! The final missing piece in the jigsaw is using the printf function, the one we use to print the value currently being stored in a variable. To display the value stored in the variable a you can use: printf("The value stored in a is %d",a); Note: the scanf function does not prompt for an input. You should ge...

C++ Program To Implement Bank Management System.

#include<iostream> #include<fstream> #include<cctype> #include<iomanip> #include <cstdlib> using namespace std; class account { int acno; char name[50]; int deposit; char type; public: void create_account(); //function to get data from user void show_account() const; //function to show data on screen void modify(); //function to add new data void dep(int); //function to accept amount and add to balance amount void draw(int); //function to accept amount and subtract from balance amount void report() const; //function to show data in tabular format int retacno() const; //function to return account number int retdeposit() const; //function to return balance amount char rettype() const;  //function to return type of account }; void account::create_account() { cout<<"\nEnter The Account No. : "; cin>>acno; cout<<"\n\nEnter The Name Of The Account Holder : "; cin.ig...