6 Sorting

Data Structures and Algorithms Ā· Unit 6 Ā· 8 hrs

Sorting

Exam-focused notes for Sorting (Data Structures and Algorithms, CSC211): what the TU syllabus asks and how it has actually been tested, with 10 solved past questions from this unit.

Sorting in short

This chapter studies how to arrange a list of elements into sorted order: internal and external sorting, the simple $O(n^2)$ comparison sorts (bubble, selection, insertion, shell), the faster divide and conquer sorts (merge, quick, heap), and how their efficiencies compare.

Sorting: notes

Introduction and Types of Sorting: Internal and External Sort

Sorting is the process of arranging elements into ascending, descending, or some other defined order. Internal sorting rearranges data that fits entirely in the computer's primary memory; external sorting is used when the data is too large for memory and must be sorted while held in secondary storage, reading and merging it in chunks. Sorting matters because a sorted list is far cheaper to search than an unsorted one, and binary search needs a sorted list to work at all; dictionaries, book indexes, directory listings and bank statements are all kept sorted for exactly this reason.

Comparison Sorting Algorithms: Bubble, Selection and Insertion Sort, Shell Sort

Bubble sort repeatedly scans the list, comparing each element with its right neighbour and swapping them if they are out of order, so that on every pass the largest remaining element "bubbles" to its correct position at the end.

void bubbleSort(int a[], int n) {
    int i, j, temp;
    for (i = 0; i < n - 1; i++)
        for (j = 0; j < n - i - 1; j++)
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
}

Trace on $[5, 2, 9, 1]$, sorting ascending:

PassComparisons (swap if out of order)Array after pass
1(5,2) swap, (5,9) no, (9,1) swap2, 5, 1, 9
2(2,5) no, (5,1) swap2, 1, 5, 9
3(2,1) swap1, 2, 5, 9

Sorted result: $[1, 2, 5, 9]$. The inner loop runs $(n-1)+(n-2)+\cdots+1 = \frac{n(n-1)}{2}$ times, giving worst and average case $O(n^2)$; the best case, an already sorted list, is $O(n)$ if the algorithm stops early on a pass with no swaps. Space complexity is $O(1)$, since only one temporary variable is used for the swap.

Selection sort repeatedly finds the smallest element in the remaining unsorted part of the list and swaps it into its correct position at the front.

void selectionSort(int a[], int n) {
    int i, j, minIdx, temp;
    for (i = 0; i < n - 1; i++) {
        minIdx = i;
        for (j = i + 1; j < n; j++)
            if (a[j] < a[minIdx]) minIdx = j;
        temp = a[i]; a[i] = a[minIdx]; a[minIdx] = temp;
    }
}

Trace on $[5, 2, 9, 1]$: pass 1 finds the minimum of the whole list, $1$ at index 3, and swaps it with index 0, giving $[1, 2, 9, 5]$; pass 2 finds the minimum of $[2, 9, 5]$, which is $2$ already at index 1, no visible change; pass 3 finds the minimum of $[9, 5]$, which is $5$ at index 3, and swaps it with index 2, giving $[1, 2, 5, 9]$. Selection sort is $O(n^2)$ in every case, since it always scans the entire remaining sub-list to find the minimum regardless of the input's order, but it performs at most $n-1$ swaps in total, fewer than bubble sort.

Insertion sort grows a sorted portion at the front of the list one element at a time, inserting each new element from the unsorted portion into its correct place among the elements already sorted.

void insertionSort(int a[], int n) {
    int i, j, key;
    for (i = 1; i < n; i++) {
        key = a[i];
        j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

Trace on $[5, 2, 9, 1]$: start with $5$ sorted alone; insert $2$ before $5$, giving $[2, 5, 9, 1]$; insert $9$, already greater than $5$, so no shift, giving $[2, 5, 9, 1]$; insert $1$, which shifts past $9$, $5$ and $2$ to the front, giving $[1, 2, 5, 9]$. Insertion sort has worst and average case $O(n^2)$, but its best case, an already sorted list, is $O(n)$ because the inner while loop never executes; it is generally preferred over bubble and selection sort for small or nearly sorted lists.

What this unit covers

  • Introduction and Types of sorting: Internal and External sort
  • Comparison Sorting Algorithms: Bubble, Selection and Insertion Sort, Shell Sort
  • Divide and Conquer Sorting: Merge, Quick and Heap Sort
  • Efficiency of Sorting Algorithms

Comparison Sorting Algorithms

2081 Ā· 5 marks

Sort the number {82, 73, 12, 39, 26, 88, 2, 9, 60, 41} using shell sort. [5]

Show solved answer

Shell Sort: {82, 73, 12, 39, 26, 88, 2, 9, 60, 41}

Given

Index0123456789
Value827312392688296041
  • $n = 10$
  • Increment sequence chosen: $k = 5, 2, 1$ (standard $n/2$ halving)

Solution

Pass 1: Increment $k = 5$

Sub-files (elements 5 positions apart):

Sub-fileIndicesValuesSorted
10, 5{82, 88}{82, 88}
21, 6{73, 2}{2, 73}
32, 7{12, 9}{9, 12}
43, 8{39, 60}{39, 60}
54, 9{26, 41}{26, 41}

Array after Pass 1:

Index0123456789
Value822939268873126041

Pass 2: Increment $k = 2$

Sub-files (elements 2 positions apart):

  • Even indices ${0,2,4,6,8}$: {82, 9, 26, 73, 60} $\rightarrow$ {9, 26, 60, 73, 82}
  • Odd indices ${1,3,5,7,9}$: {2, 39, 88, 12, 41} $\rightarrow$ {2, 12, 39, 41, 88}

Interleave back:

Index0123456789
Value922612603973418288

Pass 3: Increment $k = 1$ (standard insertion sort)

Start: {9, 2, 26, 12, 60, 39, 73, 41, 82, 88}

  • Insert 2: {2, 9, 26, 12, 60, 39, 73, 41, 82, 88}
  • Insert 26: no change
  • Insert 12: {2, 9, 12, 26, 60, 39, 73, 41, 82, 88}
  • Insert 60: no change
  • Insert 39: {2, 9, 12, 26, 39, 60, 73, 41, 82, 88}
  • Insert 73: no change
  • Insert 41: {2, 9, 12, 26, 39, 41, 60, 73, 82, 88}
  • Insert 82: no change
  • Insert 88: no change

Final Sorted Array

291226394160738288

Result: ${2, 9, 12, 26, 39, 41, 60, 73, 82, 88}$

Open this answer on its own page →

2080 Ā· 5 marks

Trace selection sort algorithm with array of numbers 2, 81, 6, 45, 11, 21, 23, 41, and 11. [5]

Array to sort (9 elements): $$[2,\ 81,\ 6,\ 45,\ 11,\ 21,\ 23,\ 41,\ 11]$$ Index 0 1 2 3 4 5 6 7 8 ----------------------------------------- Value 2 81 6 45 11 21 23 41 11 Sorting ascending. --- Method: Selection sort finds the minimum in the unsorted portion and swaps it with the first unsorted ...

Open this answer on its own page →

2080 Ā· 5 marks

Write a program to implement insertion sort. [5]

Insertion sort builds the sorted array one element at a time by picking each element and inserting it into its correct position among the already-sorted elements. The worst case time complexity is O(n²), but best case is O(n) (already sorted array). --- --- --- Pass key Array State --------------...

Open this answer on its own page →

2079 Ā· 5 marks

Sort the numbers 82, 73, 12, 39, 26, 88, 2, 9, 60, 41 using shell sort. [5]

Array (n = 10), 1-indexed: Index 1 2 3 4 5 6 7 8 9 10 -------------------------------------- Value 82 73 12 39 26 88 2 9 60 41 Increment sequence chosen: $k = 5, 3, 1$ (the standard textbook choice $\lfloor n/2 \rfloor, \dots$; here fixed to 5, 3, 1 as commonly used in TU notes). --- Sub-files (i...

Open this answer on its own page →

2078 Ā· 5 marks

Hand test selection sort with array of numbers 4, 71, 32, 19, 61, 2, -5 in descending order. [5]

Given data: - Array: $[4, 71, 32, 19, 61, 2, -5]$ - Number of elements: $n = 7$ - Sort order: Descending - Algorithm: Selection Sort --- Selection sort (descending): In each pass, find the largest element in the unsorted portion and swap it to the front of that portion. Index 0 1 2 3 4 5 6 ------...

Open this answer on its own page →

2077 Ā· 5 marks

Hand test bubble sort with array of numbers 53, 42, 78, 3, 5, 2, 15 in ascending order. [5]

Array (7 elements): $53, 42, 78, 3, 5, 2, 15$ Task: Sort in ascending order using bubble sort. Rule: Compare adjacent pairs $a[i]$ and $a[i+1]$; swap if $a[i] a[i+1]$. After each pass, the largest unsorted element bubbles to its correct position. --- Comparison Result Array ----------------------...

Open this answer on its own page →

2074 Ā· 5 marks

What do you mean by sorting? Explain the Bubble sort with example. [5]

Show solved answer

Sorting and Bubble Sort

What is Sorting?

Sorting is the process of arranging data elements in a specific order (either ascending or descending) so that the data can be searched, accessed, or processed more efficiently. Sorting organizes a collection of data into a sequence ordered by some criterion.

Example: Arranging [5, 2, 8, 1, 9] into [1, 2, 5, 8, 9] (ascending order).


Bubble Sort

Definition: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. The basic idea is to pass through the array sequentially several times. Each pass consists of comparing each element a[i] with its adjacent element a[i+1] and interchanging them if they are not in proper order.

After each pass, the largest unsorted element "bubbles up" to its correct position at the end of the array.

Algorithm

for i = 0 to n-2:
    for j = 0 to n-2-i:
        if a[j] > a[j+1]:
            swap(a[j], a[j+1])

Time Complexity

CaseComplexity
Best CaseO(n^2)
Average CaseO(n^2)
Worst CaseO(n^2)

Worked Example

Array: [5, 3, 8, 1, 4]

Pass 1 (i = 0)

StepComparisonArray State
j=05 > 3? Yes, swap[3, 5, 8, 1, 4]
j=15 > 8? No[3, 5, 8, 1, 4]
j=28 > 1? Yes, swap[3, 5, 1, 8, 4]
j=38 > 4? Yes, swap[3, 5, 1, 4, 8]

Largest element 8 is now at its correct position.

Pass 2 (i = 1)

StepComparisonArray State
j=03 > 5? No[3, 5, 1, 4, 8]
j=15 > 1? Yes, swap[3, 1, 5, 4, 8]
j=25 > 4? Yes, swap[3, 1, 4, 5, 8]

Second largest element 5 is now at its correct position.

Pass 3 (i = 2)

StepComparisonArray State
j=03 > 1? Yes, swap[1, 3, 4, 5, 8]
j=13 > 4? No[1, 3, 4, 5, 8]

Pass 4 (i = 3)

StepComparisonArray State
j=01 > 3? No[1, 3, 4, 5, 8]

Final Sorted Array

[1, 3, 4, 5, 8]

Summary

  • Bubble sort is simple but inefficient for large datasets due to O(n^2) complexity.
  • It performs a maximum of n-1 passes for an array of n elements.
  • It is an in-place sorting algorithm (no extra memory required).
Open this answer on its own page →

Divide and Conquer Sorting

2079 Ā· 5 marks

In which case the position of pivot element in quick sort always either in the last or the first position? Create a max heap from the numbers {10,12,53,34,23,77,59,66,5,8}. [5]

  • Numbers to build max heap: ${10, 12, 53, 34, 23, 77, 59, 66, 5, 8}$ (10 elements) --- The pivot ends up in the first or last position after partitioning when the array is already sorted (ascending or descending), assuming the pivot is chosen as the first (or last) element. - Ascending sorted ...
Open this answer on its own page →

2078 Ā· 5 marks

Write short notes on: a. Divide and Conquer sorting b. AVL Tree [5]

--- Divide and Conquer is an important problem-solving technique that makes use of recursion. It consists of two main parts: - Divide: The original problem is broken into smaller sub-problems, which are solved recursively. - Conquer: The solutions to the sub-problems are combined to form the solu...

Open this answer on its own page →

2075 Ā· 10 marks

Explain concept of divide and conquer algorithm. Hand test quick sort algorithm with array of numbers (78, 34, 21, 43, 7, 18, 9, 56, 38, 19). What is time complexity of quick sort algorithm?[10]

  • Array to sort: $(78, 34, 21, 43, 7, 18, 9, 56, 38, 19)$, 10 elements. - Tasks: explain divide and conquer, hand-test quick sort, state time complexity. --- Divide and conquer is an algorithm design paradigm that solves a problem by recursively breaking it into smaller independent sub-problems. ...
Open this answer on its own page →