6 Sorting Algorithms

Data Structures and Algorithms ยท Unit 6

Sorting Algorithms

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

Sorting Algorithms in short

Sorting means arranging data in a fixed order, such as smallest to largest. Sorted data is easier to search, compare and report. This chapter covers quick sort and merge sort, the two main fast methods.

Sorting Algorithms: notes

Sorting problem definition

The sorting problem is stated as follows. Given a list of $n$ items, rearrange them so that each item is not larger than the next (ascending order). The reverse order is descending.

Some terms used when comparing sorting methods:

  • In-place: the method uses only a small constant amount of extra memory.
  • Stable: items with equal keys stay in their original relative order.
  • Internal sort: all data fits in main memory. External sort: data is on disk and is sorted in parts.

Why sorting is needed

  • Searching in sorted data is much faster. Binary search takes $O(\log n)$ against $O(n)$ for linear search.
  • Sorted data makes it easy to find the smallest, largest, median and duplicates.
  • Reports and lists, such as a merit list or a phone book, must be shown in order.
  • Many other algorithms, such as merging two lists, need sorted input.
  • Databases use sorting for indexes, joins and ordered output.

Quick sort algorithm and tracing

Quick sort is a divide and conquer method. It picks a pivot and partitions the array. Smaller items go to the left of the pivot and larger items to the right. Then it sorts the two parts by recursion.

void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }

int partition(int a[], int low, int high) {
    int pivot = a[low];
    int i = low, j = high;
    while (i < j) {
        while (a[i] <= pivot && i < high) i++;   // move right
        while (a[j] > pivot) j--;                // move left
        if (i < j) swap(&a[i], &a[j]);
    }
    swap(&a[low], &a[j]);                        // place pivot
    return j;
}

void quickSort(int a[], int low, int high) {
    if (low < high) {
        int p = partition(a, low, high);
        quickSort(a, low, p - 1);
        quickSort(a, p + 1, high);
    }
}

Trace. Sort 50, 30, 10, 90, 40, 20, 60 with the first item as pivot.

First partition, pivot = 50:

  • i moves right and stops at 90. j moves left and stops at 20. Swap them: 50, 30, 10, 20, 40, 90, 60.
  • i moves on and stops at 90 again (index 5). j moves left and stops at 40 (index 4). Now $i > j$, so the loop ends.
  • Swap the pivot with a[j]: 40, 30, 10, 20, 50, 90, 60. The pivot 50 is in its final place.

Now sort the left part 40, 30, 10, 20 and the right part 90, 60.

  • Left part, pivot 40: no item is larger, so the pivot goes to the end of the part: 20, 30, 10, 40.
  • Part 20, 30, 10, pivot 20: i stops at 30, j stops at 10, swap, then swap the pivot into place: 10, 20, 30.
  • Right part 90, 60, pivot 90: result 60, 90.

Final result: 10, 20, 30, 40, 50, 60, 90.

What this unit covers

  • Sorting problem definition
  • Quick sort algorithm and tracing
  • Quick sort time complexity analysis
  • Pivot selection and limitations
  • Merge sort algorithm and tracing
  • Merge sort time complexity analysis
  • Why sorting is needed

Why sorting is needed

2082 ยท 10 marks

Why do we need sorting?Trace the Quick sort for the input {12, -9, 56, 23, 4, 8, 6, 9, 23, 21}.[2+8]

(a) Why Do We Need Sorting? Sorting arranges data in a defined order (ascending or descending). We need it because: 1. Faster searching: Sorted data enables Binary Search ($O(\log n)$) instead of linear search ($O(n)$). 2. Data organization/presentation: Easier to read, analyze, and display (rank...

Open this answer on its own page โ†’

Merge sort algorithm and tracing

2080 ยท 10 marks

Discuss the limitation of choosing first element as pivot in quick sort. Using merge sort algorithm, sort the numbers 40, 6, 5,21, 3, 100, 90, 7, 8, 12, 30.[10]

  • Array to sort: 40, 6, 5, 21, 3, 100, 90, 7, 8, 12, 30 (11 elements) - Sorting method: Merge Sort - Discussion topic: limitation of first-element pivot in Quick Sort --- Quick Sort selects a pivot and partitions the array into elements smaller and larger than the pivot. The choice of pivot criti...
Open this answer on its own page โ†’

2078 ยท 10 marks

Explain merge sort along with its time complexity. Use this algorithm to sort array of numbers given below: 25, 37, 48, 25, 23, 17, 31, 45, 7, 21, 15, 8, 11[10]

Array to sort (n = 13): $$[25,\ 37,\ 48,\ 25,\ 23,\ 17,\ 31,\ 45,\ 7,\ 21,\ 15,\ 8,\ 11]$$ Indices 0 to 12. No values missing; --- Merge Sort is a divide and conquer algorithm. It: - Divides the array into two halves. - Conquers by recursively sorting each half. - Combines by merging the two sort...

Open this answer on its own page โ†’

Quick sort algorithm and tracing

2079 ยท 10 marks

Explain quick sort algorithm. Use this algorithm to sort the numbers 35, 82, 18, 54, 13, 31, 20, 69, and 19.[10]

Quick Sort is a divide-and-conquer sorting algorithm. It selects a pivot element and partitions the array so that all elements less than or equal to the pivot are on its left, and all greater elements are on its right. The pivot is then in its final sorted position. The two partitions are sorted ...

Open this answer on its own page โ†’

0 ยท 10 marks

Define sorting problem. Trace quick sort algorithm for the following given list of data and also discuss about its time complexity: 78 45 23 89 65 12 90 33[10]

Show solved answer

Sorting Problem and Quick Sort

Definition of Sorting Problem

The sorting problem is stated as:

  • Input: A sequence of $n$ numbers $\langle a_1, a_2, \dots, a_n \rangle$.
  • Output: A permutation (rearrangement) $\langle a_1', a_2', \dots, a_n' \rangle$ of the input such that $a_1' \le a_2' \le \dots \le a_n'$.

That is, given an unordered list, arrange its elements in non-decreasing (or non-increasing) order.

Given Data

List to sort:

$$78,\ 45,\ 23,\ 89,\ 65,\ 12,\ 90,\ 33$$

Indices $[0..7]$.

Quick Sort Concept

Quick Sort is a divide-and-conquer algorithm:

  1. Choose a pivot.
  2. Partition so that smaller elements go left, larger go right; the pivot lands in its final sorted position.
  3. Recursively sort the left and right subarrays.

I use the first element as pivot with the standard Lomuto/Hoare-style scan.

Tracing Quick Sort

Pass 1: partition(A, 0, 7), pivot = 78

Array: 78 45 23 89 65 12 90 33

  • Move i right while A[i] <= 78: 45, 23 pass; A[3]=89 > 78 โ†’ stop, i = 3.
  • Move j left while A[j] > 78: A[7]=33 not > 78 โ†’ stop, j = 7.
  • i < j โ†’ swap A[3]=89 and A[7]=33:

78 45 23 33 65 12 90 89

  • Continue i: 33, 65, 12 pass; A[6]=90 > 78 โ†’ stop, i = 6.
  • Continue j: A[7]=89 > 78 โ†’ j=6; A[6]=90 > 78 โ†’ j=5; A[5]=12 not > 78 โ†’ stop, j = 5.
  • i (6) < j (5)? No โ†’ stop. Swap pivot A[0] with A[5]:

12 45 23 33 65 78 90 89 โ†’ pivot 78 fixed at index 5.

Left subarray: indices [0..4] = 12 45 23 33 65 Right subarray: indices [6..7] = 90 89

Pass 2a: partition(A, 0, 4), pivot = 12

12 45 23 33 65

  • i right while A[i] <= 12: A[0]=12 passes; A[1]=45 > 12 โ†’ stop, i = 1.
  • j left while A[j] > 12: 65, 33, 23, 45 all > 12; A[0]=12 not > 12 โ†’ stop, j = 0.
  • i (1) < j (0)? No โ†’ swap pivot A[0] with A[0] (itself).

12 45 23 33 65 78 90 89 โ†’ 12 fixed at index 0.

Left subarray [0..-1] empty; right subarray [1..4] = 45 23 33 65.

Pass 2b: partition(A, 1, 4), pivot = 45

45 23 33 65

  • i right while A[i] <= 45: 45, 23, 33 pass; A[4]=65 > 45 โ†’ stop, i = 4.
  • j left while A[j] > 45: A[4]=65 > 45 โ†’ j=3; A[3]=33 not > 45 โ†’ stop, j = 3.
  • i (4) < j (3)? No โ†’ swap pivot A[1] with A[3]:

Swap A[1]=45 and A[3]=33:

12 33 23 45 65 78 90 89 โ†’ 45 fixed at index 3.

Left subarray [1..2] = 33 23; right subarray [4..4] = 65 (single element, sorted).

Pass 3: partition(A, 1, 2), pivot = 33

33 23

  • i right while A[i] <= 33: A[1]=33 passes; A[2]=23 <= 33 passes โ†’ i = 3 (out of range).
  • j left while A[j] > 33: A[2]=23 not > 33 โ†’ stop, j = 2.
  • i (3) < j (2)? No โ†’ swap pivot A[1] with A[2]:

Swap A[1]=33 and A[2]=23:

12 23 33 45 65 78 90 89 โ†’ 33 fixed at index 2.

Left [1..1] = 23 sorted; right [3..2] empty.

Pass 4: partition(A, 6, 7), pivot = 90

90 89

  • i right while A[i] <= 90: A[6]=90 passes, A[7]=89 passes โ†’ i = 8 (out of range).
  • j left while A[j] > 90: A[7]=89 not > 90 โ†’ stop, j = 7.
  • i (8) < j (7)? No โ†’ swap pivot A[6] with A[7]:

Swap A[6]=90 and A[7]=89:

12 23 33 45 65 78 89 90 โ†’ 90 fixed at index 7.

Left [6..6] = 89 sorted; right empty.

Final Sorted List

$$\boxed{12,\ 23,\ 33,\ 45,\ 65,\ 78,\ 89,\ 90}$$

Time Complexity

Let $T(n)$ be the running time. Partitioning an array of size $n$ costs $\Theta(n)$.

Best case: Pivot splits the array into two nearly equal halves.

$$T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n)$$

Average case: For random inputs the split is balanced enough that

$$T(n) = \Theta(n \log n)$$

Worst case: Pivot is always the smallest/largest element (e.g. already sorted data with first-element pivot), giving splits of size $0$ and $n-1$:

$$T(n) = T(n-1) + \Theta(n) = \Theta(n^2)$$

Space complexity: $O(\log n)$ average recursion stack, $O(n)$ worst case; it is an in-place sort.

CaseTime
Best$\Theta(n\log n)$
Average$\Theta(n\log n)$
Worst$\Theta(n^2)$
Open this answer on its own page โ†’