0% found this document useful (0 votes)
10 views

unit 3 ds

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

unit 3 ds

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Unit-3

Sorting And Searching


Searching
The process of finding the desired information from the set of items stored in the form of elements in the
computer memory is referred to as ‘searching in data structure’. These sets of items are in various forms, such
as an array, tree, graph, or linked list.
Searching Methods
Searching in the data structure can be done by implementing searching algorithms to check for or retrieve an
element from any form of stored data structure.

Searching Algorithms are designed to check for an element or retrieve an


element from any data structure where it is stored. Based on the type of search
operation, these algorithms are generally classified into two categories:

• Sequential search
The array or list of elements is traversed sequentially while checking every component of the set.
For example: Linear Search.
Linear Search to find the element “20” in a given list of numbers

• Interval Search
Algorithms designed explicitly for searching in sorted data structures are included in the interval search. The
efficiency of these algorithms is far better than linear search algorithms.
For example: Binary Search.
Binary Search to find the element “23” in a given list of numbers

Linear Search
Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element
of a list until the desired element is found, otherwise the search continues till the end of the data set. It is the
easiest searching algorithm.
Algorithm
Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the first element in the list.
Step 3 - If both are matched, then display "Given element is found!!!" and terminate the function
Step 4 - If both are not matched, then compare search element with the next element in the list.
Step 5 - Repeat steps 3 and 4 until search element is compared with last element in the list.
Step 6 - If last element in the list also doesn't match, then display "Element is not found!!!" and terminate
the function.
Working of Linear search
To understand the working of linear search algorithm, let's take an unsorted array. It will be easy to understand
the working of linear search with an example.
Let the elements of array are -

Let the element to be searched is K = 41


Now, start from the first element and compare K with each element of the array.

The value of K, i.e., 41, is not matched with the first element of the array. So, move to the next element. And
follow the same process until the respective element is found.
Now, the element to be searched is found. So algorithm will return the index of the element matched.
Linear search program in C
#include<stdio.h>
#include<conio.h>

void main(){
int list[20],size,i,sElement;

printf("Enter size of the list: ");


scanf("%d",&size);

printf("Enter any %d integer values: ",size);


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

printf("Enter the element to be Search: ");


scanf("%d",&sElement);

// Linear Search Logic


for(i = 0; i < size; i++)
{
if(sElement == list[i])
{
printf("Element is found at %d index", i);
break;
}
}
if(i == size)
printf("Given element is not found in the list!!!");
getch();
}
Binary Search
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on
the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the
sorted form.
Binary search follows the divide and conquer approach in which the list is divided into two halves, and the
item is compared with the middle element of the list. If the match is found then, the location of the middle
element is returned. Otherwise, we search into either of the halves depending upon the result produced through
the match.
Algorithm
Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element in the sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and terminate the function.
Step 5 - If both are not matched, then check whether the search element is smaller or larger than the
middle element.
Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5 for the left sublist
of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5 for the right sublist
of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until sublist contains only
one element.
Step 9 - If that element also doesn't match with the search element, then display "Element is not found in
the list!!!" and terminate the function.
Working of Binary search
Now, let's see the working of the Binary Search Algorithm.
To understand the working of the Binary search algorithm, let's take a sorted array. It will be easy to
understand the working of Binary search with an example.
Binary search follows the divide and conquer approach.
Let the elements of array are -

Let the element to search is, K = 56


We have to use the below formula to calculate the mid of the array -
1. mid = (beg + end)/2
So, in the given array -
beg = 0
end = 8
mid = (0 + 8)/2 = 4. So, 4 is the mid of the array.

Now, the element to search is found. So algorithm will return the index of the element matched.
Implementation of Binary Search Algorithm using C Programming Language
#include<stdio.h>
#include<conio.h>

void main()
{
int first, last, middle, size, i, sElement, list[100];
clrscr();

printf("Enter the size of the list: ");


scanf("%d",&size);
printf("Enter %d integer values in Assending order\n", size);

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


scanf("%d",&list[i]);

printf("Enter value to be search: ");


scanf("%d", &sElement);

first = 0;
last = size - 1;
middle = (first+last)/2;

while (first <= last) {


if (list[middle] < sElement)
first = middle + 1;
else if (list[middle] == sElement) {
printf("Element found at index %d.\n",middle);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Element Not found in the list.");
getch();
}

Static Hashing
In all search techniques like linear search, binary search and search trees, the time required to search an
element depends on the total number of elements present in that data structure. In all these search techniques,
as the number of elements increases the time required to search an element also increases linearly.

Hashing is another approach in which time required to search an element doesn't depend on the total number of
elements. Using hashing data structure, a given element is searched with constant time complexity. Hashing
is an effective way to reduce the number of comparisons to search an element in a data structure.

Hashing is defined as follows...


Hashing is the process of indexing and retrieving element (data) in a data structure to provide a faster
way of finding the element using a hash key.

Here, the hash key is a value which provides the index value where the actual data is likely to be stored in the
data structure.

In this data structure, we use a concept called Hash table to store data. All the data values are inserted into the
hash table based on the hash key value. The hash key value is used to map the data with an index in the hash
table. And the hash key is generated for every data using a hash function. That means every entry in the hash
table is based on the hash key value generated using the hash function.

Hash Table is defined as follows...


Hash table is just an array which maps a key (data) into the data structure with the help of hash
function such that insertion, deletion and search operations are performed with constant time
complexity (i.e. O(1)).

Hash tables are used to perform insertion, deletion and search operations very quickly in a data structure.
Using hash table concept, insertion, deletion, and search operations are accomplished in constant time
complexity. Generally, every hash table makes use of a function called hash function to map the data into the
hash table.

A hash function is defined as follows...


Hash function is a function which takes a piece of data (i.e. key) as input and produces an integer (i.e.
hash value) as output which maps the data to a particular index in the hash table.

Basic concept of hashing and hash table is shown in the following figure...

Sorting
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier
to search through it quickly and easily. The simplest example of sorting is a dictionary. Sorting refers to the
operation or technique of arranging and rearranging sets of data in some specific order. A Sorting Algorithm is
used to rearrange a given array or list of elements according to a comparison operator on the elements. The
comparison operator is used to decide the new order of elements in the respective data structure.
Sorting Algorithms
A sorting algorithm is just a series of orders or instructions. In this, an array is an input, on which the sorting
algorithm performs operations to give out a sorted array.Sorting algorithms are described in the following table
along with the description.
Importance Of Sorting In Data Structure
Sorting in DS actually provides users with several benefits. For example, when you are performing sorting on
elements, many complications such as min/max, kth smallest/largest get automatically simplified.
Furthermore, sorting also provides you with many algorithmic solutions, some of which might include divide
and conquer, iterative, and recursive-based.
• Bubble Sort
• Insertion Sort
• Quick Sort
• Selection Sort
• Merge Sort
• Heap Sort
Insertion Sort-
Insertion sort falls under one of the most popular sorting types in data structure. It is basically an algorithm that
helps to place an unsorted element at its suitable position in each iteration. It’s similar to the way you sort your
cards during a card game. The first card is usually considered to be already sorted, and the next card that you
pick up is then compared against the first one. Based on the first card, you wither place the unsorted second
card on the right or left side of the former one. The insertion sort follows the same approach.
Algorithm
Step 1 - Assume that first element in the list is in sorted portion and all the remaining elements are in unsorted
portion.
Step 2: Take first element from the unsorted portion and insert that element into the sorted portion in the order
specified.
Step 3: Repeat the above process until all the elements from the unsorted portion are moved into the sorted
portion.
Example
Consider an example: arr[]: {12, 11, 13, 5, 6}

12 11 13 5 6

First Pass:
Initially, the first two elements of the array are compared in insertion sort.

12 11 13 5 6

Here, 12 is greater than 11 hence they are not in the ascending order and 12 is not at its correct position.
Thus, swap 11 and 12.
So, for now 11 is stored in a sorted sub-array.

11 12 13 5 6

Second Pass:
Now, move to the next two elements and compare them

11 12 13 5 6

Here, 13 is greater than 12, thus both elements seems to be in ascending order, hence, no swapping will
occur. 12 also stored in a sorted sub-array along with 11
Third Pass:
Now, two elements are present in the sorted sub-array which are 11 and 12
Moving forward to the next two elements which are 13 and 5

11 12 13 5 6

Both 5 and 13 are not present at their correct place so swap them

11 12 5 13 6

After swapping, elements 12 and 5 are not sorted, thus swap again

11 5 12 13 6

Here, again 11 and 5 are not sorted, hence swap again

5 11 12 13 6

here, it is at its correct position


Fourth Pass:
Now, the elements which are present in the sorted sub-array are 5, 11 and 12
Moving to the next two elements 13 and 6

5 11 12 13 6

Clearly, they are not sorted, thus perform swap between both

5 11 12 6 13
Now, 6 is smaller than 12, hence, swap again

5 11 6 12 13

Here, also swapping makes 11 and 6 unsorted hence, swap again

5 6 11 12 13

Finally, the array is completely sorted.


Illustrations:

Implementaion of Insertion Sort Algorithm using C Programming Language


#include<stdio.h>
#include<conio.h>

void main(){

int size, i, j, temp, list[100];

printf("Enter the size of the list: ");


scanf("%d", &size);

printf("Enter %d integer values: ", size);


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

//Insertion sort logic


for (i = 1; i < size; i++) {
temp = list[i];
j = i - 1;
while ((temp < list[j]) && (j >= 0)) {
list[j + 1] = list[j];
j = j - 1;
}
list[j + 1] = temp;
}

printf("List after Sorting is: ");


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

getch();
}

Selection Sort
In selection sort, the first element in the list is selected and it is compared repeatedly with all the remaining
elements in the list. If any element is smaller than the selected element (for Ascending order), then both are
swapped so that first position is filled with the smallest element in the sorted order. Next, we select the element
at a second position in the list and it is compared with all the remaining elements in the list. If any element is
smaller than the selected element, then both are swapped. This procedure is repeated until the entire list is
sorted.
Algorithm
Step 1 - Select the first element of the list (i.e., Element at first position in the list).
Step 2: Compare the selected element with all the other elements in the list.
Step 3: In every comparision, if any element is found smaller than the selected element (for Ascending order),
then both are swapped.
Step 4: Repeat the same procedure with element in the next position in the list till the entire list is sorted.
Example
Complexity of the Selection Sort Algorithm
To sort an unsorted list with 'n' number of elements, we need to make ((n-1)+(n-2)+(n-3)+......+1) = (n (n-
1))/2 number of comparisions in the worst case. If the list is already sorted then it requires 'n' number of
comparisions.
Worst Case : O(n2)
Best Case : Ω(n2)
Average Case : Θ(n2)
Implementaion of Selection Sort Algorithm using C Programming Language
#include<stdio.h>
#include<conio.h>
void main(){
int size,i,j,temp,list[100];
clrscr();
printf("Enter the size of the List: ");
scanf("%d",&size);
printf("Enter %d integer values: ",size);
for(i=0; i<size; i++)
scanf("%d",&list[i]);
//Selection sort logic
for(i=0; i<size; i++){
for(j=i+1; j<size; j++){
if(list[i] > list[j])
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
}
}
printf("List after sorting is: ");
for(i=0; i<size; i++)
printf(" %d",list[i]);
getch();
}

Bubble Sort
It is the easiest and simplest of all the sorting algorithms. It works on the principle of repeatedly swapping
adjacent elements in case they are not in the right order. It performs sorting by repeatedly moving the largest
element to the highest index of the array. It comprises of comparing each element to its adjacent element and
replaces them accordingly.
In simpler terms, if the input is to be sorted in ascending order, the bubble sort will first compare the first two
elements in the array. In case the second one is smaller than the first, it will swap the two, and move on to the
next element, and so on.
Working of Bubble Sort
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
1. Starting from the first index, compare the first and the second elements.
2. If the first element is greater than the second element, they are swapped.
3. Now, compare the second and the third elements. Swap them if they are not in order.
4. The above process goes on until the last element.
5. Compare the Adjacent Elements
2. Remaining Iteration
The same process goes on for the remaining iterations.
After each iteration, the largest element among the unsorted elements is placed at the end.

Put the largest element at the end


In each iteration, the comparison takes place up to the last unsorted element.
Compare the adjacent elements
The array is sorted when all the unsorted elements are placed at their correct positions.

The array is sorted if all elements are kept in the right order
C Program for Bubble Sort Using for Loop
#include <stdio.h>
int main(){
int arr[50], num, x, y, temp;
printf("Please Enter the Number of Elements you want in the array: ");
scanf("%d", &num);
printf("Please Enter the Value of Elements: ");
for(x = 0; x < num; x++)
scanf("%d", &arr[x]);
for(x = 0; x < num - 1; x++){
for(y = 0; y < num - x - 1; y++){
if(arr[y] > arr[y + 1]){
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
printf("Array after implementing bubble sort: ");
for(x = 0; x < num; x++){
printf("%d ", arr[x]);
}
return 0;
}
C Program for Bubble Sort Using Functions
#include <stdio.h>
void bubbleSortExample(int arr[], int num){
int x, y, temp;
for(x = 0; x < num - 1; x++){
for(y = 0; y < num - x - 1; y++){
if(arr[y] > arr[y + 1]){
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
}
int main(){
int arr[50], n, x;
printf("Please Enter the Number of Elements you want in the array: ");
scanf("%d", &n);
printf("Please Enter the Value of Elements: ");
for(x = 0; x < n; x++)
scanf("%d", &arr[x]);
bubbleSortExample(arr, n);
printf("Array after implementing bubble sort: ");
for(x = 0; x < n; x++){
printf("%d ", arr[x]);
}
return 0;
}

Quick Sort -
Quick sort is a fast sorting algorithm used to sort a list of elements. Quick sort algorithm is invented by C. A.
R. Hoare.
The quick sort algorithm attempts to separate the list of elements into two parts and then sort each part
recursively. That means it use divide and conquer strategy. In quick sort, the partition of the list is performed
based on the element called pivot. Here pivot element is one of the elements in the list.
The list is divided into two partitions such that "all elements to the left of pivot are smaller than the pivot
and all elements to the right of pivot are greater than or equal to the pivot".
Algorithm:
Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in the list).
Step 2 - Define two variables i and j. Set i and j to first and last elements of the list respectively.
Step 3 - Increment i until list[i] > pivot then stop.
Step 4 - Decrement j until list[j] < pivot then stop.
Step 5 - If i < j then exchange list[i] and list[j].
Step 6 - Repeat steps 3,4 & 5 until i > j.
Step 7 - Exchange the pivot element with list[j] element.
Example
Complexity of the Quick Sort Algorithm
To sort an unsorted list with 'n' number of elements, we need to make ((n-1)+(n-2)+(n-3)+......+1) = (n (n-
1))/2 number of comparisions in the worst case. If the list is already sorted, then it requires 'n' number of
comparisions.
Worst Case : O(n2)
Best Case : O (n log n)
Average Case : O (n log n)
Implementation of Quick Sort Algorithm using C Programming Language
#include<stdio.h>
#include<conio.h>
void quickSort(int [10],int,int);
void main(){
int list[20],size,i;
printf("Enter size of the list: ");
scanf("%d",&size);
printf("Enter %d integer values: ",size);
for(i = 0; i < size; i++)
scanf("%d",&list[i]);
quickSort(list,0,size-1);
printf("List after sorting is: ");
for(i = 0; i < size; i++)
printf(" %d",list[i]);
getch();
}
void quickSort(int list[10],int first,int last){
int pivot,i,j,temp;
if(first < last){
pivot = first;
i = first;
j = last;
while(i < j){
while(list[i] <= list[pivot] && i < last)
i++;
while(list[j] > list[pivot])
j--;
if(i <j){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
quickSort(list,first,j-1);
quickSort(list,j+1,last);
}
}
Merge Sort
This algorithm works on splitting an array into two halves of comparable sizes. Each half is then sorted and
merged back together by using the merge () function.It takes a time of (n logn) in the worst case.
Algorithm for Merge Sort
Step 1: Find the middle index of the array.
Middle = 1 + (last – first)/2
Step 2: Divide the array from the middle.
Step 3: Call merge sort for the first half of the array
MergeSort(array, first, middle)
Step 4: Call merge sort for the second half of the array.
MergeSort(array, middle+1, last)
Step 5: Merge the two sorted halves into a single sorted array.
Working of Merge Sort
Consider an array having the following elements: 1,6,3,2,7,5,8,4. We need to sort this array using merge sort.

There is a total of 8 elements in the array. Thus, mid = 4. So we will first divide this array into two arrays of
size 4 as shown:

Next, we recursively divide these arrays into further halves. The half of 4 is 2. So, now we have 4 arrays of
size 2 each.

We will keep on dividing into further halves until we have reached an array length of size 1 as shown:
After this, we have the combining step. We will compare each element with its consecutive elements and
arrange them in a sorted manner.

In the next iteration, we will compare two arrays and sort them as shown:

Finally, we will compare the elements of the two arrays each of size 4 and we will get our resultant sorted
array as shown:

Time Complexity
Best Case Complexity: O(n*log n)
Worst Case Complexity: O(n*log n)
Average Case Complexity: O(n*log n)
Implementation of Merge Sort in C
#include <stdio.h>
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arrays
/* copy data to temp arrays */
for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];
i = 0; /* initial index of first sub-array */
j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */
while (i < n1 && j < n2)
{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
/* Function to print the array */
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}
Max Heap
Max heap data structure is a specialized full binary tree data structure. In a max heap nodes are arranged based
on node value.
Max heap is defined as - “Max heap is a specialized full binary tree in which every parent node contains
greater or equal value than its child nodes.”
Example

Above tree is satisfying both Ordering property and Structural property according to the Max Heap data
structure.
Operations on Max Heap
The following operations are performed on a Max heap data structure...
1. Finding Maximum
2. Insertion
3. Deletion
Finding Maximum Value Operation in Max Heap
Finding the node which has maximum value in a max heap is very simple. In a max heap, the root node has the
maximum value than all other nodes. So, directly we can display root node value as the maximum value in
max heap.
Insertion Operation in Max Heap
Insertion Operation in max heap is performed as follows...
• Step 1 - Insert the newNode as last leaf from left to right.
• Step 2 - Compare newNode value with its Parent node.
• Step 3 - If newNode value is greater than its parent, then swap both of them.
• Step 4 - Repeat step 2 and step 3 until newNode value is less than its parent node (or) newNode
reaches to root.
Example
Consider the above max heap. Insert a new node with value 85.
• Step 1 - Insert the newNode with value 85 as last leaf from left to right. That means newNode is
added as a right child of node with value 75. After adding max heap is as follows...

• Step 2 - Compare newNode value (85) with its Parent node value (75). That means 85 > 75

• Step 3 - Here newNode value (85) is greater than its parent value (75), then swap both of them.
After swapping, max heap is as follows...
• Step 4 - Now, again compare newNode value (85) with its parent node value (89).

Here, newNode value (85) is smaller than its parent node value (89). So, we stop insertion process.
Finally, max heap after insertion of a new node with value 85 is as follows...

Deletion Operation in Max Heap


In a max heap, deleting the last node is very simple as it does not disturb max heap properties.

Deleting root node from a max heap is little difficult as it disturbs the max heap properties. We use the
following steps to delete the root node from a max heap...
Step 1 - Swap the root node with last node in max heap
Step 2 - Delete last node.
Step 3 - Now, compare root value with its left child value.
Step 4 - If root value is smaller than its left child, then compare left child with its right sibling. Else
goto Step 6
Step 5 - If left child value is larger than its right sibling, then swap root with left child otherwise swap
root with its right child.
Step 6 - If root value is larger than its left child, then compare root value with its right child value.
Step 7 - If root value is smaller than its right child, then swap root with right child otherwise stop the
process.
Step 8 - Repeat the same until root node fixes at its exact position.
Example
Consider the above max heap. Delete root node (90) from the max heap.
• Step 1 - Swap the root node (90) with last node 75 in max heap. After swapping max heap is as
follows...

• Step 2 - Delete last node. Here the last node is 90. After deleting node with value 90 from heap, max
heap is as follows...

• Step 3 - Compare root node (75) with its left child (89).
Here, root value (75) is smaller than its left child value (89). So, compare left child (89) with its right
sibling (70).

• Step 4 - Here, left child value (89) is larger than its right sibling (70), So, swap root (75) with left
child (89).

• Step 5 - Now, again compare 75 with its left child (36).


Here, node with value 75 is larger than its left child. So, we compare node 75 with its right child 85.

• Step 6 - Here, node with value 75 is smaller than its right child (85). So, we swap both of them. After
swapping max heap is as follows...

• Step 7 - Now, compare node with value 75 with its left child (15).
Here, node with value 75 is larger than its left child (15) and it does not have right child. So we stop the
process.

Finally, max heap after deleting root node (90) is as follows...

Heap Sort
Heap sort is one of the sorting algorithms used to arrange a list of elements in order. Heapsort algorithm uses
one of the tree concepts called Heap Tree. In this sorting algorithm, we use Max Heap to arrange list of
elements in Descending order and Min Heap to arrange list elements in Ascending order.
Algorithm
The Heap sort algorithm to arrange a list of elements in ascending order is performed using following steps...
Step 1 - Construct a Binary Tree with given list of Elements.
Step 2 - Transform the Binary Tree into Min Heap.
Step 3 - Delete the root element from Min Heap using Heapify method.
Step 4 - Put the deleted element into the Sorted list.
Step 5 - Repeat the same until Min Heap becomes empty.
Step 6 - Display the sorted list.
Example
Complexity of the Heap Sort Algorithm
To sort an unsorted list with 'n' number of elements, following are the complexities...
Worst Case : O(n log n)
Best Case : O(n log n)
Average Case : O(n log n)
Program to implement heap sort in C language
#include <stdio.h>
/* function to heapify a subtree. Here 'i' is the
index of root node in array a[], and 'n' is the size of heap. */
void heapify(int a[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
int right = 2 * i + 2; // right child
// If left child is larger than root
if (left < n && a[left] > a[largest])
largest = left;
// If right child is larger than root
if (right < n && a[right] > a[largest])
largest = right;
// If root is not largest
if (largest != i) {
// swap a[i] with a[largest]
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;

heapify(a, n, largest);
}
}
/*Function to implement the heap sort*/
void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/
// swap a[0] with a[i]
int temp = a[0];
a[0] = a[i];
a[i] = temp;

heapify(a, i, 0);
}
}
/* function to print the array elements */
void printArr(int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d", arr[i]);
printf(" ");
}

}
int main()
{
int a[] = {48, 10, 23, 43, 28, 26, 1};
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
heapSort(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}

Radix Sort Algorithm


Radix sort is one of the sorting algorithms used to sort a list of integer numbers in order. In radix sort
algorithm, a list of integer numbers will be sorted based on the digits of individual numbers. Sorting is
performed from least significant digit to the most significant digit.
Radix sort algorithm requires the number of passes which are equal to the number of digits present in the
largest number among the list of numbers. For example, if the largest number is a 3 digit number then that
list is sorted with 3 passes.
Step by Step Process

The Radix sort algorithm is performed using the following steps...

• Step 1 - Define 10 queues each representing a bucket for each digit from 0 to 9.

• Step 2 - Consider the least significant digit of each number in the list which is to be sorted.

• Step 3 - Insert each number into their respective queue based on the least significant digit.

• Step 4 - Group all the numbers from queue 0 to queue 9 in the order they have inserted into their

respective queues.

• Step 5 - Repeat from step 3 based on the next least significant digit.

• Step 6 - Repeat from step 2 until all the numbers are grouped based on the most significant digit.

Example
Complexity of the Radix Sort Algorithm

To sort an unsorted list with 'n' number of elements, Radix sort algorithm needs the following

complexities...

Worst Case : O(n)

Best Case : O(n)

Average Case : O(n)

Implementation of Radix Sort Algorithm using C Programming


Language
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int getMax(int list[], int n) {


int mx = list[0];
int i;
for (i = 1; i < n; i++)
if (list[i] > mx)
mx = list[i];
return mx;
}

void countSort(int list[], int n, int exp) {


int output[n];
int i, count[10] = { 0 };

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


count[(list[i] / exp) % 10]++;

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


count[i] += count[i - 1];

for (i = n - 1; i >= 0; i--) {


output[count[(list[i] / exp) % 10] - 1] = list[i];
count[(list[i] / exp) % 10]--;
}

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


list[i] = output[i];
}

void radixsort(int list[], int n) {


int m = getMax(list, n);

int exp;
for (exp = 1; m / exp > 0; exp *= 10)
countSort(list, n, exp);
}

void print(int list[], int n) {


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

int main()
{
int list[] = { 82, 901, 100, 12, 150, 77, 55, 23 };
int i, n = sizeof(list) / sizeof(list[0]);

printf("List of numbers before sort: \n");


for(i = 0; i<8; i++)
printf("%d\t", list[i] );

radixsort(list, n);

printf("\n\nList of numbers after sort: \n");


print(list, n);
printf("\n\n");
return 0;
}

You might also like