You are on page 1of 36

Presentation

Sorting algorithms
(heap, shell, radix, bucket)
SUBMITTED to:
Mam Farheen
Presented by:
M.HASEEB.ULLAH.AHMAD
Sorting algorithm

A sorting algorithm is a method for reorganizing a large number of items


into a specific order, such as alphabetical, highest-to-lowest value or
shortest-to-longest distance. Sorting algorithms take lists of items as
input data, perform specific operations on those lists and deliver ordered
arrays as output. The many applications of sorting algorithms include
organizing items by price on a retail website and determining the order of
sites on a search engine results page (SERP).
Heap-sort

In computer science, heapsort is a comparison-based sorting algorithm.


Heapsort can be thought of as an improved selection sort: like selection
sort, heapsort divides its input into a sorted and an unsorted region, and it
iteratively shrinks the unsorted region by extracting the largest element
from it and inserting it into the sorted region. Unlike selection sort,
heapsort does not waste time with a linear-time scan of the unsorted
region; rather, heap sort maintains the unsorted region in a heap data
structure to more quickly find the largest element in each step.
C++ Program to implement Heap Sort

#include <iostream>

using namespace std;

// A function to heapify the array.


void MaxHeapify(int a[], int i, int n)
{
int j, temp;
temp = a[i];
j = 2*i;

while (j <= n)
{
if (j < n && a[j+1] > a[j])
j = j+1;
// Break if parent value is already greater than child value.
if (temp > a[j])
break;
// Switching value with the parent node if temp < a[j].
else if (temp <= a[j])
{
a[j/2] = a[j];
j = 2*j;
}
}
a[j/2] = temp;
return;
}
void HeapSort(int a[], int n)
{
int i, temp;
for (i = n; i >= 2; i--)
{
// Storing maximum value at the end.
temp = a[i];
a[i] = a[1];
a[1] = temp;
// Building max heap of remaining element.
MaxHeapify(a, 1, i - 1);
}
}
void Build_MaxHeap(int a[], int n)
{
int i;
for(i = n/2; i >= 1; i--)
MaxHeapify(a, i, n);
}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
n++;
int arr[n];
for(i = 1; i < n; i++)
{
cout<<"Enter element "<<i<<": ";
cin>>arr[i];
}
// Building max heap.
Build_MaxHeap(arr, n-1);
HeapSort(arr, n-1);

// Printing the sorted data.


cout<<"\nSorted Data ";

for (i = 1; i < n; i++)


cout<<"->"<<arr[i];

return 0;
Program Explanation

1. Take input of data.


2. Call Build_MaxHeap() function with ‘arr’ the array of data and ‘n-1’ the
number of values, in the argument list.
3. After building the max heap call HeapSort().
4. Switch the root value of heap with the last index value of array since
root value is highest among all.
5. Decrement the last index value.
6. Repeat it for all the element.
7. Return to main and display the result.
8. Exit.
Shell-sort

Shellsort, also known as Shell sort or Shell's method, is an in-place


comparison sort. It can be seen as either a generalization of sorting by
exchange (bubble sort) or sorting by insertion (insertion sort).The method
starts by sorting pairs of elements far apart from each other, then
progressively reducing the gap between elements to be compared.
C++ Program to Implement Shell Sort

#include<iostream>

using namespace std;

// A function implementing Shell sort.


void ShellSort(int a[], int n)
{
int i, j, k, temp;
// Gap 'i' between index of the element to be compared, initially n/2.
for(i = n/2; i > 0; i = i/2)
{
for(j = i; j < n; j++)
{
for(k = j-i; k >= 0; k = k-i)
{
// If value at higher index is greater, then
break the loop.
if(a[k+i] >= a[k])
break;
// Switch the values otherwise.
else
{
temp = a[k];
a[k] = a[k+i];
a[k+i] = temp;
}
}
}
}
}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

ShellSort(arr, n);

// Printing the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];

return 0;
Program Explanation

1. Take input of data.


2. Call ShellSort() function with ‘arr’ the array of data and ‘n’ the number
of values, in the argument list.
3. Implement Sorting algorithm using nested for loop.
4. The first loop will run on ‘i’ Which decides the gap value to compare
two elements.
5. The second loop will run on ‘j’ from i to n-1.
6. The third loop will run on ‘k’ and sort the element having i as a gap
between their index.
7. Switch the values if arr[k] < arr[k-i]. 8. Return to main and display the
result. 9. Exit.
Radix-sort

In computer science, radix sort is a non-comparative sorting algorithm. It


avoids comparison by creating and distributing elements into buckets
according to their radix. For elements with more than one significant
digit, this bucketing process is repeated for each digit, while preserving
the ordering of the prior step, until all digits have been considered. For
this reason, radix sort has also been called bucket sort and digital sort.
C++ Program to Implement Radix Sort

#include <iostream>

using namespace std;

// Get maximum value from array.


int getMax(int arr[], int n)
{
int max = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}

// Count sort of arr[].


void countSort(int arr[], int n, int exp)
{
// Count[i] array will be counting the number of array values having that 'i' digit at their (exp)th
place.
int output[n], i, count[10] = {0};

// Count the number of times each digit occurred at (exp)th place in every input.
for (i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;

// Calculating their cumulative count.


for (i = 1; i < 10; i++)
count[i] += count[i-1];

// Inserting values according to the digit '(arr[i] / exp) % 10' fetched into count[(arr[i] / exp) %
10].
for (i = n - 1; i >= 0; i--)
{
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

// Assigning the result to the arr pointer of main().


for (i = 0; i < n; i++)
arr[i] = output[i];
}

// Sort arr[] of size n using Radix Sort.


void radixsort(int arr[], int n)
{
int exp, m;
m = getMax(arr, n);
// Calling countSort() for digit at (exp)th place in every input.
for (exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

radixsort(arr, n);

// Printing the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
Program Explanation

1. Take input of data.


2. Get the maximum of input data.
3. Run the countSort() till (m/exp) > 0.
4. Sort the data on the basis of the digit at (exp)th place.
5. Assign the sorted data back to arr[] array.
6. Check the condition in step 3.
7. If false, print the sorted output.
8. Exit.
Bucket-sort

Bucket sort, or bin sort, is a sorting algorithm that works by distributing


the elements of an array into a number of buckets. Each bucket is then
sorted individually, either using a different sorting algorithm, or by
recursively applying the bucket sorting algorithm. It is a distribution sort, a
generalization of pigeonhole sort, and is a cousin of radix sort in the most-
to-least significant digit flavor. Bucket sort can be implemented with
comparisons and therefore can also be considered a comparison sort
algorithm.
C++ Program to Implement Bucket Sort

#include <iostream>

using namespace std;

// A structure to represent a node.


struct Node
{
int value;
struct Node* next;
};

// A structure to represent a Head Bucket Node of the bucket list.


struct Bucket
{
// Pointer to head node of Bucket.
struct Node *head;
};

struct BucketList
{
int V;
struct Bucket * array;
};

// A utility function to create a new node for a particular entry in a bucket.


struct Node* newNode(int value)
{
struct Node* newnode = new Node;
newnode->value = value;
newnode->next = NULL;
return newnode;
}

// A utility function that creates a list of the bucket over the range of input data.
struct BucketList* createBucket(int V)
{
int i;
struct BucketList* bl = new BucketList;

bl->V = V;
bl->array = new Bucket[V];

// Initialize each Bucket list as empty by making head as NULL.


for(i = 0; i < V; i++)
bl->array[i].head = NULL;
return bl;
}

// A function to Insert the nodes to corresponding Buckets.


void addNode(struct BucketList* bl, int bckt, int value)
{
// Creating new data node.
struct Node *newnode = newNode(value);
struct Node *temp = new Node;

if(bl->array[bckt].head != NULL)
{
temp = bl->array[bckt].head;

// Sorting.
// If the head node value is lesser than the newnode value, then add node at beginning.
if(temp->value > newnode->value)
{
newnode->next = bl->array[bckt].head;
bl->array[bckt].head = newnode;
}
else
{
// Search for the node whose value is more than the newnode value.
while(temp->next != NULL)
{
if((temp->next)->value > newnode->value)
break;
temp = temp->next;
}

// Insert newnode after temp node.


newnode->next = temp->next;
temp->next = newnode;
}
}
else
{
// Assign head of the Bucket as newnode since bucket head is NULL.
bl->array[bckt].head = newnode;
}
// A function to print the result as sorted Data.
void printBuckets(struct BucketList *bl)
{
int v;
struct Node* pCrawl = new Node;

for(v = 0; v < bl->V; v++)


{
// To view the data in individual bucket remove next line from comment.
// cout<<"\n\t bucket "<<v+1;

pCrawl = bl->array[v].head;
while (pCrawl != NULL)
{
cout<<"->"<< pCrawl->value;
pCrawl = pCrawl->next;
}
}
}

int main()
{
// Create the BucketLists for the data and set 10 as default number of Buckets.
int V = 10, range, NOE, i;
struct BucketList* mybucket = createBucket(V);

cout<<"\n\nEnter the upper limit in the power of 10 (10 or 100 or 1000 ..) to create Bucket: ";
cin>>range;

// Dividing range into 10 parts so it will have 10 buckets as default.


range = range/10;

cout<<"\nEnter the number of data element to be sorted: ";


cin>>NOE;
int arr[NOE];

for(i = 0; i < NOE; i++)


{
cout<<"Enter element "<<i+1<<" : ";
cin>>arr[i];
addNode(mybucket, arr[i]/range, arr[i]);
}
// Print the adjacency list representation of the BucketList i.e the sorted Output.
cout<<"\nSorted Data ";
printBuckets(mybucket);

return 0;
}
Program Explanation

1. Create Node, Bucket and BucketList structures.


2. Take range and data, which should be uniformly distributed over the
range.
3. Allocate memory to their objects accordingly.
4. Insert the data into the list according to their value which comes out to
dividing data into the bucket.
5. Sort data using insertion sort in the linked lists.
6. Display the result.
7. Exit.
THANKS

You might also like