Home » AKTU CSE Notes » AKTU Data Structure Unit 3 Notes KCS 301

AKTU Data Structure Unit 3 Notes KCS 301

Last updated:

Support this post with a reaction:

4,660 views

Looking for AKTU Data Structure Unit 3 Notes KCS 301? Here, you can find complete and easy-to-understand notes for Unit 3 of the AKTU Data Structures subject. These notes are prepared for B.Tech students to help them understand important concepts, prepare for semester examinations, and revise all the topics covered in the KCS 301 syllabus.

On this page, you will find unit-wise study material, important concepts, explanations, algorithms, examples, C programs, and time complexity analysis to support your AKTU exam preparation. Whether you are preparing for your semester examination or revising important topics, these AKTU Data Structure Notes will help you study in a simple and organized way.

Unit 3 of Data Structures focuses on three important concepts: Searching, Hashing, and Sorting. Searching techniques are used to find specific elements in a collection of data. This unit covers Sequential Search, Index Sequential Search, and Binary Search, along with their working principles and algorithms.

Additionally, you will learn different sorting algorithms, including Insertion Sort, Selection Sort, Bubble Sort, Quick Sort, Merge Sort, Heap Sort, and Radix Sort. These algorithms help arrange data in ascending or descending order and are important for understanding efficient data organization and processing.

AKTU Data Structure UNIT 3 Syllabus

Searching: Concept of Searching, Sequential search, Index Sequential Search, Binary Search.
Concept of Hashing & Collision resolution Techniques used in Hashing.

Sorting: Insertion Sort,
Selection, Bubble Sort, Quick Sort, Merge Sort, Heap Sort and Radix Sort.

Searching – Concept and Introduction

Searching is the process of finding the location of a particular element, known as the Search Key, in a collection of data.

The main objective of searching is to determine whether a particular element exists in a data structure and, if it exists, to identify its position or index.

Searching is one of the fundamental operations in data structures because it helps retrieve specific information from a collection of data efficiently.

Example of searching

Consider the array:

A = [10, 20, 30, 40, 50]

Search key = 30

The element 30 is present at index 2 (zero-based indexing).

Therefore, the search operation returns index 2.

Types of Searching

Searching MethodDescription
Linear SearchChecks elements one by one.
Index Sequential SearchUses an index to locate a block and then searches within it.
Binary SearchRepeatedly divides a sorted array into halves.

Applications of Searching

  1. Student Record Management: Finding student details using roll numbers or names.
  2. E-commerce Applications: Searching for products based on product names or IDs.
  3. Database Management: Retrieving specific records from large databases.
  4. Operating Systems: Searching for files and folders.
  5. Mobile Applications: Finding contacts using names or phone numbers.
  6. Information Retrieval: Finding specific information from large collections of data.

1.Linear Search (Sequential Search)

Linear Search is a simple searching algorithm that checks each element of an array sequentially until the required element is found or the end of the array is reached. It is also known as Sequential Search because elements are examined one after another in a sequence.

Linear Search can be performed on both sorted and unsorted arrays.

Working Principle of Linear Search

The following steps explain how Linear Search works:

  1. Start searching from the first element of the array.
  2. Compare the current element with the given search key.
  3. If both elements are equal, return the index of the element.
  4. If they are not equal, move to the next element.
  5. Repeat the comparison until the element is found or the end of the array is reached.
  6. If the element is not found after checking all elements, return -1.

Example of Linear search

Array:

A = [12, 25, 18, 40, 32]

Search key = 40

StepCurrent ElementComparisonResult
11212 ≠ 40Continue
22525 ≠ 40Continue
31818 ≠ 40Continue
44040 = 40Found

Result: Element 40 is found at index 3.

Algorithm for Linear Search

LINEAR_SEARCH(A, n, key)
{
    for i = 0 to n - 1
    {
        if A[i] == key
            return i
    }

    return -1
}

C Program for Linear Search

This program searches for a given element in an array using the Linear Search technique by comparing each element sequentially. If the element is found, it returns its index; otherwise, it returns -1.

This program searches for the element 40 in the array {10, 20, 30, 40, 50} using Linear Search. It compares each element sequentially and returns index 3 when the element is found.


#include <stdio.h>

int main()
{
    int arr[] = {10, 20, 30, 40, 50};
    int n = 5;
    int key = 40;
    int found = -1;

    for (int i = 0; i < n; i++)
    {
        if (arr[i] == key)
        {
            found = i;
            break;
        }
    }

    if (found != -1)
        printf("Element found at index %d", found);
    else
        printf("Element not found");

    return 0;
}

2.Index Sequential Search

Index Sequential Search is a searching technique that combines sequential searching with an indexing mechanism.

The sorted data is divided into blocks, and an index table is created to store the key (usually the first or smallest key) of each block along with its address.

The index is used to identify the block in which the required element may exist. After locating the appropriate block, a sequential search is performed within that block to find the required element.

Working Principle of Index Sequential Search

  1. Divide the sorted data into blocks.
  2. Create an index table containing the first element of each block.
  3. Search the index table for the appropriate block.
  4. Perform sequential search within that block.
  5. Return the position if the key is found.

Example of Index Sequential Search

Consider the sorted array:

A = [10, 15, 20, 30, 35, 40, 50, 60, 70]

Divide the array into three blocks.

BlockElementsIndex Value
Block 110, 15, 2020
Block 230, 35, 4040
Block 350, 60, 7070

Search key = 35

Step 1: Search the index table.

Since 35 lies between 20 and 40, select Block 2.

Step 2: Perform sequential search inside Block 2.

  • Compare 30 with 35.
  • Compare 35 with 35.
  • Element found.

Result: 35 is located in Block 2.

Algorithm of Index Sequential Search

INDEX_SEQUENTIAL_SEARCH(A, n, key)
{
    Create index table for blocks

    Find the block whose range contains key

    if no block is found
        return NOT_FOUND

    Perform linear search in selected block

    if key is found
        return position

    return NOT_FOUND
}

C Program for Index Sequential Search


#include <stdio.h>

int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
    int n = 9, key = 50;
    int blockSize = 3;
    int found = -1;

    // Index table stores the last element of each block
    int index[] = {30, 60, 90};
    int blocks = 3;

    // Find the appropriate block
    for (int i = 0; i < blocks; i++)
    {
        if (key <= index[i])
        {
            int start = i * blockSize;
            int end = start + blockSize;

            // Sequential search within the block
            for (int j = start; j < end && j < n; j++)
            {
                if (arr[j] == key)
                {
                    found = j;
                    break;
                }
            }
            break;
        }
    }

    if (found != -1)
        printf("Element found at index %d", found);
    else
        printf("Element not found");

    return 0;
}

Complexity Analysis of Index Sequential Search

Let:

  • n = total number of elements
  • b = number of blocks
  • m = number of elements per block

If the index is searched linearly:

T(n)=O(b+m) T(n)=O(b+m)

If the index is searched using Binary Search:

T(n)=O(log⁡b+m)T(n)=O(\log b+m)

3.Binary Search

Binary Search is an efficient searching algorithm that finds a particular element in a sorted array by repeatedly dividing the search interval into two halves.

It follows the Divide and Conquer technique, in which the search space is reduced by half in every iteration until the required element is found or the search interval becomes empty.

Conditions for Binary Search

  • The data must be sorted.
  • The elements should support comparison.
  • Random access is preferred, such as in arrays.

Working Principle of Binary search

  1. Find the middle element of the array.
  2. Compare the search key with the middle element.
  3. If the key equals the middle element, return its index.
  4. If the key is smaller, search the left half.
  5. If the key is greater, search the right half.
  6. Repeat until the element is found or the search interval becomes empty.
StepLowHighMidA[Mid]Action
10634060 > 40, search right
246560Element found

Result: 60 is found at index 5.

Binary Search Algorithm – Iterative

BINARY_SEARCH(A, n, key)
{
    low = 0
    high = n - 1

    while low <= high
    {
        mid = low + (high - low) / 2

        if A[mid] == key
            return mid

        else if key < A[mid]
            high = mid - 1

        else
            low = mid + 1
    }

    return -1
}

Binary Search Program in C (Iterative)

This program searches for the element 50 in the sorted array {10, 20, 30, 40, 50, 60, 70} using iterative Binary Search. It repeatedly divides the search interval into halves and returns index 4 when the element is found.

#include <stdio.h>

int binarySearch(int arr[], int n, int key)
{
    int low = 0, high = n - 1;

    while (low <= high)
    {
        int mid = low + (high - low) / 2;

        if (arr[mid] == key)
            return mid;

        else if (key < arr[mid])
            high = mid - 1;

        else
            low = mid + 1;
    }

    return -1;
}

int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60, 70};
    int n = 7;
    int key = 50;

    int result = binarySearch(arr, n, key);

    if (result != -1)
        printf("Element found at index %d", result);
    else
        printf("Element not found");

    return 0;
}
Output:
Element found at index 4

Recursive Binary Search Alogrithm

BINARY_SEARCH(A, low, high, key)
{
    if low > high
        return -1

    mid = low + (high - low) / 2

    if A[mid] == key
        return mid

    if key < A[mid]
        return BINARY_SEARCH(A, low, mid - 1, key)

    else
        return BINARY_SEARCH(A, mid + 1, high, key)
}

Recursive Binary Search Program in C

This program searches for the element 50 in the sorted array {10, 20, 30, 40, 50, 60, 70} using Recursive Binary Search. The function repeatedly calls itself with a reduced search interval until the element is found at index 4 or the search interval becomes empty.

#include <stdio.h>

int binarySearch(int arr[], int low, int high, int key)
{
    if (low > high)
        return -1;

    int mid = low + (high - low) / 2;

    if (arr[mid] == key)
        return mid;

    if (key < arr[mid])
        return binarySearch(arr, low, mid - 1, key);

    else
        return binarySearch(arr, mid + 1, high, key);
}

int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60, 70};
    int n = 7;
    int key = 50;

    int result = binarySearch(arr, 0, n - 1, key);

    if (result != -1)
        printf("Element found at index %d", result);
    else
        printf("Element not found");

    return 0;
}
Output:
Element found at index 4

What Is Hashing in Data Structures?

Hashing is a technique used in data structures to store, organize, and retrieve data efficiently. It works by converting a given key into a specific index or address using a mathematical function called a hash function. The generated index determines the location where the corresponding data is stored in a data structure called a hash table.

Hashing provides fast access to data because elements can be stored and retrieved using their calculated positions instead of searching through all the elements one by one.

For example, consider a student database in which each student has a unique roll number. Instead of checking every student record to find a particular student, a hash function can calculate the storage location using the roll number.

Basic Components of Hashing

Collision: A situation in which two or more different keys generate the same hash value..

Key: A value used to identify a particular record, such as a student roll number or employee ID.

Hash Function: A mathematical function that converts a key into an index in the hash table.

Hash Table: A data structure that stores elements at positions calculated by the hash function.

Hash Value: The index or address generated by applying the hash function to a key.

Note: A collision occurs when multiple keys are mapped to the same index. Collision resolution techniques are used to handle this situation.

Hashing Structure

Example of Hashing

Consider the keys:

12, 22, 32, 42

Hash table size = 10

Hash function:

h(k)=kmod10 h(k)=k mod 10
KeyCalculationIndex
1212 mod 102
2222 mod 102
3232 mod 102
4242 mod 102

All keys map to index 2.

This situation is called a collision.

Hash Functions and Hash Tables

1.Hash Function

A hash function is a mathematical function that converts a given key into an index in a hash table. It determines the position where the corresponding data should be stored.

h(k)=Indexh(k)=\text{Index}

A good hash function should:

  • Be simple to compute.
  • Distribute keys uniformly.
  • Minimize collisions.
  • Produce valid table indices.

Types of Hash Functions

1. Division Method

The key is divided by the table size, and the remainder is used as the index.

h(k)=kmodmh(k)=k \bmod m

Example of Division Method:

  • Key = 25
  • Table size = 7

Index = 4.

h(25)=25mod7=4h(25)=25 \bmod 7=4
2. Multiplication Method

In the multiplication method, the key is multiplied by a constant fractional value. The fractional part of the result is used to calculate the hash index.

h(k)=⌊m(kAmod1)⌋ h(k)=\lfloor m(kA \bmod 1)\rfloor

Where:

  • m = table size
  • A = constant between 0 and 1
  • k = key
3. Mid-Square Method

In the mid-square method, the key is squared, and the middle digits of the resulting number are extracted to generate the hash index.

In this method:

  1. Square the key.
  2. Extract the middle digits.
  3. Use the extracted digits as the hash index.

Example of Mid-Square Method:

Key = 25

252=62525^2=625

Middle digit = 2

Hash index = 2, assuming the chosen extraction scheme and table size support it.

4. Folding Method

In the folding method, the key is divided into multiple parts of equal or suitable length. These parts are added together to generate the hash value.

Example of Folding Method:

Key = 123456

Divide into parts:

12 + 34 + 56 = 102

If the table size is 10:

h(k)=102mod10=2 h(k)=102 \bmod 10=2

Hash index = 2.

2.Hash Table

A hash table is a data structure that stores data in the form of key-value pairs. It uses a hash function to calculate the index at which each key-value pair should be stored.

The hash function helps in performing insertion, searching, and deletion operations efficiently.

  • Key: Identifies a record.
  • Index: Represents the position where the data is stored in the hash table.
  • Value: Contains the actual information associated with the key .

Example of Hash Table:

Consider a hash table of size 5 containing the following keys:

IndexKey
018
121
232
343
4Empty
  • Index 0: The key 18 is stored at position 0.
  • Index 1: The key 21 is stored at position 1.
  • Index 2: The key 32 is stored at position 2.
  • Index 3: The key 43 is stored at position 3.
  • Index 4: No key is stored at this position, so it is empty.

Here, each key is stored at a particular index in the hash table.

Hash Table Operations

  • Insertion: Adds a new key-value pair to the hash table at the index calculated by the hash function.
  • Searching: Finds a particular key by calculating its hash index and checking the corresponding location.
  • Deletion: Removes a particular key from the hash table.

Collision Resolution Techniques in Hashing

A collision occurs when two or more keys generate the same hash table index.

Example:

h(k)=kmod10 h(k)=k \bmod 10

Collision resolution techniques are used to handle collisions and store all keys correctly.

Types of Collision Resolution Techniques

The major techniques are:

  1. Separate Chaining
  2. Open Addressing
    • Linear Probing
    • Quadratic Probing
    • Double Hashing

1.Separate Chaining

Separate Chaining is a collision resolution technique in which multiple elements that generate the same hash index are stored using a linked list or another collection.

Hash function:

h(k)=kmod10 h(k)=k \bmod 10

Keys: 15, 25, 35

All three keys map to index 5.

Working of Separate Chaining
  • Insert 15 at index 5.
  • Insert 25 at index 5. Since index 5 is already occupied, add 25 to the linked list at that index.
  • Insert 35 at index 5. Add 35 to the same linked list.

2.Open Addressing

Open Addressing is a collision resolution technique in which all elements are stored directly inside the hash table.

When a collision occurs, the algorithm searches for another empty position using a probing technique.

The main types of Open Addressing are:

A. Linear Probing

Linear Probing is a collision resolution technique that checks the next consecutive position in the hash table until an empty position is found.

Formula:

hi(k)=(h(k)+i)modmh_i(k)=(h(k)+i)\bmod m

Where:

  • k = key
  • m = table size
  • i = probe number

Example of Linear Probing

Hash table size = 10

h(k)=kmod10 h(k)=k \bmod 10

Hash function:

Insert keys: 23, 43, 13, 33

B. Quadratic Probing

Quadratic Probing is a collision resolution technique that uses a quadratic function to calculate the next available position in the hash table.

Instead of checking consecutive positions, it checks positions using squared probe numbers.

Formula:

hi(k)=(h(k)+c1i+c2i2)modm h_i(k)=(h(k)+c_1i+c_2i^2)\bmod m
C. Double Hashing

Double Hashing is a collision resolution technique that uses two different hash functions to calculate the next position when a collision occurs.

The first hash function determines the initial index, while the second hash function determines the step size for probing.

Formula:

hi(k)=(h1(k)+i×h2(k))modm h_i(k)=(h_1(k)+i\times h_2(k))\bmod m

Insertion Sort

Insertion Sort is a simple comparison-based sorting algorithm that builds a sorted array one element at a time.

It works similarly to arranging playing cards in your hand.

Insertion Sort

Working Principle of Insertion Sort

  1. Assume the first element is sorted.
  2. Select the next element as the key.
  3. Compare the key with elements in the sorted portion.
  4. Shift larger elements one position to the right.
  5. Insert the key at its correct position.
  6. Repeat until all elements are sorted.

Algorithm of Insertion Sort

INSERTION_SORT(A, n)
{
    for i = 1 to n - 1
    {
        key = A[i]
        j = i - 1

        while j >= 0 AND A[j] > key
        {
            A[j + 1] = A[j]
            j = j - 1
        }

        A[j + 1] = key
    }
}

Insertion Sort Program in C

#include <stdio.h>

void insertionSort(int arr[], int n)
{
    int i, key, j;

    for (i = 1; i < n; i++)
    {
        key = arr[i];
        j = i - 1;

        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j--;
        }

        arr[j + 1] = key;
    }
}

int main()
{
    int arr[] = {5, 3, 4, 1, 2};
    int n = 5;

    insertionSort(arr, n);

    printf("Sorted Array: ");

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

    return 0;
}

Example of Insertion Sort

Consider the following array:

Array: [5, 2, 4, 6, 1]

The array is sorted by selecting one element at a time and inserting it into its correct position.

Initial Array:

5, 2, 4, 6, 1

Pass 1: Select 2 as the key. Compare it with 5. Since 5 is greater than 2, shift 5 one position to the right and insert 2 at the beginning.

2, 5, 4, 6, 1

Pass 2: Select 4 as the key. Compare it with 5 and shift 5 one position to the right. Insert 4 before 5.

2, 4, 5, 6, 1

Pass 3: Select 6 as the key. Compare it with 5. Since 5 is smaller than 6, no shifting is required. Keep 6 in its current position.

2, 4, 5, 6, 1

Pass 4: Select 1 as the key. Compare it with 6, 5, 4, and 2. Shift all these elements one position to the right and insert 1 at the beginning.

1, 2, 4, 5, 6

Final Sorted Array: [1, 2, 4, 5, 6]

Selection Sort

Selection Sort is a comparison-based sorting algorithm that repeatedly selects the smallest element from the unsorted portion and places it at the beginning of that portion.

Selection Sort

Working Principle of selection sort

  1. Find the smallest element in the array.
  2. Swap it with the first element.
  3. Find the smallest element in the remaining unsorted portion.
  4. Swap it with the next position.
  5. Repeat until the array is sorted.

Algorithm of selection sort

SELECTION_SORT(A, n)
{
    for i = 0 to n - 2
    {
        min = i

        for j = i + 1 to n - 1
        {
            if A[j] < A[min]
                min = j
        }

        swap A[i] and A[min]
    }
}

Selection Sort Program in C

#include <stdio.h>

void selectionSort(int arr[], int n)
{
    int i, j, min, temp;

    for (i = 0; i < n - 1; i++)
    {
        min = i;

        for (j = i + 1; j < n; j++)
        {
            if (arr[j] < arr[min])
                min = j;
        }

        temp = arr[i];
        arr[i] = arr[min];
        arr[min] = temp;
    }
}

int main()
{
    int arr[] = {64, 25, 12, 22, 113};
    int n = 5;

    selectionSort(arr, n);

    printf("Sorted Array: ");

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

    return 0;
}

Example of Selection Sort

Consider the following array:

Array: [64, 25, 12, 22, 113]

Selection Sort repeatedly finds the smallest element from the unsorted portion and places it in its correct position.

Initial Array:

64, 25, 12, 22, 113

Pass 1: Find the smallest element in the entire array. The smallest element is 12. Swap 12 with the first element, 64.

12, 25, 64, 22, 113

Pass 2: Find the smallest element in the remaining unsorted portion [25, 64, 22, 113]. The smallest element is 22. Swap 22 with 25.

12, 22, 64, 25, 113

Pass 3: Find the smallest element in the remaining unsorted portion [64, 25, 113]. The smallest element is 25. Swap 25 with 64.

12, 22, 25, 64, 113

Pass 4: Find the smallest element in the remaining unsorted portion [64, 113]. The smallest element is 64. It is already in the correct position, so no swapping is required.

12, 22, 25, 64, 113

Final Sorted Array: [12, 22, 25, 64, 113]

Bubble Sort

Bubble Sort is a comparison-based sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order.

The largest element gradually moves to the end of the array during each pass. This process is called bubbling.

Bubble sort

Working Principle of Bubble Sort

  1. Compare the first two elements.
  2. Swap them if they are in the wrong order.
  3. Move to the next pair.
  4. Continue until the end of the array.
  5. Repeat the passes until the array is sorted.

Algorithm of Bubble Sort

BUBBLE_SORT(A, n)
{
    for i = 0 to n - 2
    {
        swapped = false

        for j = 0 to n - i - 2
        {
            if A[j] > A[j + 1]
            {
                swap A[j] and A[j + 1]
                swapped = true
            }
        }

        if swapped == false
            break
    }
}

Bubble Sort Program in C

#include <stdio.h>

void bubbleSort(int arr[], int n)
{
    int i, j, temp, swapped;

    for (i = 0; i < n - 1; i++)
    {
        swapped = 0;

        for (j = 0; j < n - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;

                swapped = 1;
            }
        }

        if (swapped == 0)
            break;
    }
}

int main()
{
    int arr[] = {64, 25, 12, 22, 11};
    int n = 5;

    bubbleSort(arr, n);

    printf("Sorted Array: ");

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

    return 0;
}

Example of Bubble Sort

Consider the following array:

Array: [64, 25, 12, 22, 11]

The array is sorted by comparing adjacent elements and swapping them whenever they are in the wrong order.

Initial Array:

64, 25, 12, 22, 11

Pass 1: Compare adjacent elements and swap them if the first element is greater than the second element.

  • Compare 64 and 25 → Swap.
  • Compare 64 and 12 → Swap.
  • Compare 64 and 22 → Swap.
  • Compare 64 and 11 → Swap.

25, 12, 22, 11, 64

Pass 2: Compare the adjacent elements in the unsorted portion.

  • Compare 25 and 12 → Swap.
  • Compare 25 and 22 → Swap.
  • Compare 25 and 11 → Swap.

12, 22, 11, 25, 64

Pass 3: Continue comparing the remaining unsorted elements.

  • Compare 12 and 22 → No swap.
  • Compare 22 and 11 → Swap.

12, 11, 22, 25, 64

Pass 4: Compare the remaining adjacent elements.

– Compare 12 and 11 → Swap.

11, 12, 22, 25, 64

Final Sorted Array: [11, 12, 22, 25, 64]

Quick Sort

Quick Sort is a comparison-based sorting algorithm that follows the Divide and Conquer approach.

It selects an element called the pivot and partitions the array into two parts:

  • Elements smaller than the pivot.
  • Elements greater than the pivot.

The two partitions are then sorted recursively.

Quick Sort

Working Principle of Quick Sort

  1. Select a pivot element.
  2. Partition the array around the pivot.
  3. Place smaller elements on the left.
  4. Place larger elements on the right.
  5. Recursively sort the left and right partitions.

Quick Sort Algorithm

QUICK_SORT(A, low, high)
{
    if low < high
    {
        p = PARTITION(A, low, high)

        QUICK_SORT(A, low, p - 1)
        QUICK_SORT(A, p + 1, high)
    }
}

It performs the following tasks:

  1. Calls the PARTITION algorithm to divide the array around a pivot.
  2. Gets the correct position of the pivot.
  3. Recursively calls QUICK_SORT for the left partition.
  4. Recursively calls QUICK_SORT for the right partition.
  5. Continues until all partitions contain zero or one element.

Partition Algorithm – Lomuto Scheme

PARTITION(A, low, high)
{
    pivot = A[high]
    i = low - 1

    for j = low to high - 1
    {
        if A[j] <= pivot
        {
            i = i + 1
            swap A[i] and A[j]
        }
    }

    swap A[i + 1] and A[high]

    return i + 1
}

It performs the following tasks:

  1. Selects the last element as the pivot.
  2. Compares each element with the pivot.
  3. Moves elements smaller than or equal to the pivot to the left side.
  4. Places elements greater than the pivot on the right side.
  5. Places the pivot in its correct sorted position.
  6. Returns the final index of the pivot.

Quick Sort Program in C

#include <stdio.h>

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int arr[], int low, int high)
{
    int pivot = arr[high];
    int i = low - 1;

    for (int j = low; j < high; j++)
    {
        if (arr[j] <= pivot)
        {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }

    swap(&arr[i + 1], &arr[high]);

    return i + 1;
}

void quickSort(int arr[], int low, int high)
{
    if (low < high)
    {
        int p = partition(arr, low, high);

        quickSort(arr, low, p - 1);
        quickSort(arr, p + 1, high);
    }
}

int main()
{
    int arr[] = {25, 12, 64, 11, 22};
    int n = 5;

    quickSort(arr, 0, n - 1);

    printf("Sorted Array: ");

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

    return 0;
}

Example of Quick Sort

Consider the following array:

Array: [25, 12, 64, 11, 22]

In this example, we use the Lomuto Partition Scheme, where the last element is selected as the pivot.

Initial Array:

25, 12, 64, 11, 22

Pass 1: Select 22 as the pivot (last element). Compare each element with the pivot and move elements smaller than or equal to 22 towards the left.

  • Compare 25 and 22 → No swap.
  • Compare 12 and 22 → Move 12 to the left.
  • Compare 64 and 22 → No swap.
  • Compare 11 and 22 → Move 11 to the left.
  • Finally, swap the pivot 22 with 25.

12, 11, 22, 25, 64

The pivot 22 is now in its correct sorted position.

Pass 2: Apply Quick Sort to the left partition [12, 11]. Select 11 as the pivot.

  • Compare 12 and 11 → No swap.
  • Swap the pivot 11 with 12.

11, 12, 22, 25, 64

Pass 3: The right partition [25, 64] contains two elements. Select 64 as the pivot.

  • Compare 25 and 64 → No swap.
  • The pivot is already in its correct position.

11, 12, 22, 25, 64

Final Sorted Array: [11, 12, 22, 25, 64]

Merge Sort

Merge Sort is a comparison-based sorting algorithm that follows the Divide and Conquer approach.

It divides the array into smaller subarrays, recursively sorts them, and merges the sorted subarrays into a single sorted array.

Merge Sort uses two algorithms: MERGE SORT and MERGE. Both perform different tasks during the sorting process.

Merge Sort

Working Principle of Merge Sort

  1. Divide the array into two halves.
  2. Recursively sort the left half.
  3. Recursively sort the right half.
  4. Merge the two sorted halves.
  5. Repeat until the complete array is sorted.

Merge Sort Algorithm

MERGE_SORT(A, low, high)
{
    if low < high
    {
        mid = (low + high) / 2

        MERGE_SORT(A, low, mid)
        MERGE_SORT(A, mid + 1, high)

        MERGE(A, low, mid, high)
    }
}

It performs the following tasks:

  1. Checks whether the array contains more than one element.
  2. Finds the middle position of the array.
  3. Divides the array into left and right halves.
  4. Recursively calls MERGE_SORT for the left half.
  5. Recursively calls MERGE_SORT for the right half.
  6. Calls the MERGE algorithm to combine the sorted subarrays.

Merge Algorithm

MERGE(A, low, mid, high)
{
    Create temporary arrays L and R

    Copy left half into L
    Copy right half into R

    Compare elements of L and R

    Copy smaller element into A

    Copy remaining elements into A
}

It performs the following tasks:

  1. Creates temporary arrays to store the left and right subarrays.
  2. Compares the first elements of both subarrays.
  3. Copies the smaller element into the original array.
  4. Continues comparing and copying until one subarray becomes empty.
  5. Copies the remaining elements into the original array.

Merge Sort Program in C

#include <stdio.h>

void merge(int arr[], int low, int mid, int high)
{
    int i = low;
    int j = mid + 1;
    int k = 0;

    int temp[high - low + 1];

    while (i <= mid && j <= high)
    {
        if (arr[i] <= arr[j])
            temp[k++] = arr[i++];
        else
            temp[k++] = arr[j++];
    }

    while (i <= mid)
        temp[k++] = arr[i++];

    while (j <= high)
        temp[k++] = arr[j++];

    for (i = low, k = 0; i <= high; i++, k++)
        arr[i] = temp[k];
}

void mergeSort(int arr[], int low, int high)
{
    if (low < high)
    {
        int mid = (low + high) / 2;

        mergeSort(arr, low, mid);
        mergeSort(arr, mid + 1, high);

        merge(arr, low, mid, high);
    }
}

int main()
{
    int arr[] = {38, 27, 43, 3, 9, 82, 10, 19};
    int n = 8;

    mergeSort(arr, 0, n - 1);

    printf("Sorted Array: ");

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

    return 0;
}

Example of Merge Sort

Consider the following array:

Array: [38, 27, 43, 3, 9, 82, 10, 19]

Merge Sort first divides the array into smaller subarrays and then merges them in sorted order.

Step 1: Divide the Array

Divide the array into two halves:

[38, 27, 43, 3] and [9, 82, 10, 19]

Step 2: Divide into Smaller Subarrays

Divide each half again:

[38, 27] [43, 3] [9, 82] [10, 19]

Divide until each subarray contains only one element:

[38] [27] [43] [3] [9] [82] [10] [19]

Step 3: Merge Single Elements

Compare and merge the individual elements in sorted order.

  • [38] and [27] → [27, 38]
  • [43] and [3] → [3, 43]
  • [9] and [82] → [9, 82]
  • [10] and [19] → [10, 19]

Step 4: Merge the Sorted Subarrays

Merge the smaller sorted subarrays:

  • [27, 38] and [3, 43] → [3, 27, 38, 43]
  • [9, 82] and [10, 19] → [9, 10, 19, 82]

Step 5: Final Merge

Merge the two sorted halves:

[3, 27, 38, 43] and [9, 10, 19, 82]

Compare the elements one by one and arrange them in ascending order.

[3, 9, 10, 19, 27, 38, 43, 82]

Heap Sort

Heap Sort is a comparison-based sorting algorithm that uses a Binary Heap data structure to sort elements. It follows the heap property to arrange elements in ascending or descending order.

A binary heap is a complete binary tree in which every parent node follows a specific relationship with its child nodes.

Types of Heaps

There are two types of binary heaps:

1. Max Heap

In a Max Heap, every parent node is greater than or equal to its child nodes. Therefore, the largest element is always present at the root node.

2. Min Heap

In a Min Heap, every parent node is smaller than or equal to its child nodes. Therefore, the smallest element is always present at the root node.

For ascending order, Heap Sort generally uses a Max Heap.

Working Principle of Heap Sort

  1. Build a Max Heap from the input array.
  2. The largest element is present at the root.
  3. Swap the root with the last element.
  4. Reduce the heap size by one.
  5. Heapify the remaining elements.
  6. Repeat until the heap is sorted.

Step 1: Build Max Heap

        10
       /  \
      5    3
     / \
    4   1

Array representation:

[10, 5, 3, 4, 1]

Step 2: Swap Root with Last Element

[1, 5, 3, 4, 10]

Heapify remaining elements.

Step 3: Repeat

Continue extracting the maximum element and placing it at the end.

Final sorted array:

[1, 3, 4, 5, 10]

Heap Sort Algorithm

HEAP_SORT(A, n)
{
    BUILD_MAX_HEAP(A, n)

    for i = n - 1 down to 1
    {
        swap A[0] and A[i]

        HEAPIFY(A, 0, i)
    }
}

Heapify Algorithm

Heapify is used to maintain the Max Heap property. It compares a parent node with its children and moves the largest element to the parent position when necessary.

HEAPIFY(A, i, n)
{
largest = i
left = 2i + 1
right = 2
i + 2

if left < n AND A[left] > A[largest]
    largest = left

if right < n AND A[right] > A[largest]
    largest = right

if largest != i
{
    swap A[i] and A[largest]

    HEAPIFY(A, largest, n)
}

}

Heap Sort Program in C

#include <stdio.h>

void heapify(int arr[], int n, int i)
{
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;
    int temp;

    if (left < n && arr[left] > arr[largest])
        largest = left;

    if (right < n && arr[right] > arr[largest])
        largest = right;

    if (largest != i)
    {
        temp = arr[i];
        arr[i] = arr[largest];
        arr[largest] = temp;

        heapify(arr, n, largest);
    }
}

void heapSort(int arr[], int n)
{
    int i, temp;

    for (i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);

    for (i = n - 1; i > 0; i--)
    {
        temp = arr[0];
        arr[0] = arr[i];
        arr[i] = temp;

        heapify(arr, i, 0);
    }
}

int main()
{
    int arr[] = {4, 10, 3, 5, 1};
    int n = 5;

    heapSort(arr, n);

    printf("Sorted Array: ");

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

    return 0;
}

Radix Sort

Radix Sort is a non-comparison-based sorting algorithm that sorts numbers by processing their digits one position at a time, starting from the least significant digit (LSD) or the most significant digit (MSD).

It commonly uses Counting Sort as a stable intermediate sorting algorithm to arrange elements based on individual digits.

It commonly uses Counting Sort as a stable intermediate sorting algorithm.

Types of Radix Sort

  1. Least Significant Digit (LSD) Radix Sort: Starts sorting from the rightmost digit (ones place) and moves towards the leftmost digit.
  2. Most Significant Digit (MSD) Radix Sort: Starts sorting from the leftmost digit (highest place value) and moves towards the rightmost digit.

1.LSD Radix Sort

LSD Radix Sort starts sorting numbers from the least significant digit and gradually moves towards the most significant digit.

Array:

[170, 45, 75, 90, 802, 24, 2, 66]

Pass 1: Sort by Ones Digit

Sorted result:

[170, 90, 802, 2, 24, 45, 75, 66]

Pass 2: Sort by Tens Digit

Sorted result:

[802, 2, 24, 45, 66, 170, 75, 90]

Pass 3: Sort by Hundreds Digit

Sorted result:

[2, 24, 45, 66, 75, 90, 170, 802]

Final sorted array:

[2, 24, 45, 66, 75, 90, 170, 802]

Algorithm of LSD Radix Sort

RADIX_SORT(A, n)
{
    max = maximum element in A

    for exp = 1; max / exp > 0; exp = exp * 10
    {
        COUNTING_SORT_BY_DIGIT(A, n, exp)
    }
}

2. Most Significant Digit (MSD) Radix Sort

MSD Radix Sort is a type of Radix Sort that starts sorting numbers from the most significant digit (leftmost digit) and gradually moves towards the least significant digit (rightmost digit).

It first groups numbers based on their leftmost digit. Then, each group is recursively sorted using the next digit until all numbers are arranged in ascending order.

Radix Sort Program in C

#include <stdio.h>

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;
}

void countingSort(int arr[], int n, int exp)
{
    int output[n];
    int count[10] = {0};

    for (int i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;

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

    for (int i = n - 1; i >= 0; i--)
    {
        int digit = (arr[i] / exp) % 10;
        output[count[digit] - 1] = arr[i];
        count[digit]--;
    }

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

void radixSort(int arr[], int n)
{
    int max = getMax(arr, n);

    for (int exp = 1; max / exp > 0; exp *= 10)
        countingSort(arr, n, exp);
}

int main()
{
    int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
    int n = 8;

    radixSort(arr, n);

    printf("Sorted Array: ");

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

    return 0;
}

Important AKTU Examination Questions – Unit 3

  • Explain Linear Search and Binary Search with algorithms, examples, and time complexity.
  • Explain Index Sequential Search with its working and complexity analysis.
  • Explain hashing and collision resolution techniques with suitable examples.
  • Explain Insertion Sort and Selection Sort with algorithms and worked examples.
  • Explain Bubble Sort and Quick Sort with algorithms and complexity analysis.
  • Explain Merge Sort using Divide and Conquer with an example.
  • Explain Heap Sort with the construction of a Max Heap and sorting procedure.
  • Explain Radix Sort with a detailed example.
  • Compare all sorting algorithms based on time complexity, space complexity, and stability.
  • Explain the different hash functions and discuss the advantages and disadvantages of hashing.

Explore More Resources of Data Structures

ResourceDescriptionLink
Data Structures Question BankPractice important questions, MCQs, and exam-oriented questions on Data Structures.Data Structure Previous Year Questions and Answers →
Data Structures Previous Year Question PapersPrepare using previous year university question papers for Data Structures.View Previous Year Papers →

Explore Other AKTU Data Structures Units

Continue your AKTU Data Structures preparation with complete unit-wise notes, explanations, diagrams, algorithms, and important questions.

Data Structure UnitNavigation
Unit 1 – Introduction to Data StructuresRead Unit 1 Notes→
Unit 2 – Stacks, Queues and RecursionRead Unit 2 Notes→
Unit 4 – Graphs and Graph AlgorithmsRead Unit 4 Notes→
Unit 5 – Trees and Binary TreesRead Unit 5 Notes→

Explore More Study Materials

Visit Quescol Home Page

Explore more AKTU B.Tech CSE notes, syllabus, and examination preparation resources on Quescol.