UNIVERSITY OF AGRICULTURE, FAISALABAD
Department of Computer Science
LECTURE 20 · STUDENT NOTES
Sorting a List: Bubble Sort & Selection Sort
CS-307 Programming Fundamentals · BSCS Semester 1
Week | Slides | Linked practical | Reference ID |
9 | Lecture20_Sorting_Bubble_Selection.pptx | Practical 14 | N20 |
Learning Outcomes
SLO | By the end of this lecture you can… | Builds CLO | Bloom level |
|---|---|---|---|
SLO 20.1 | Explain what sorting is and why a sorted list is useful | CLO1: Identify the necessary properties of good problem-solving techniques. | C2 |
SLO 20.2 | Trace and write bubble sort and selection sort, swapping with a temporary variable | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 20.3 | Compare the two sorts by passes, comparisons and swaps, and change them to sort in descending order | CLO1: Identify the necessary properties of good problem-solving techniques. | C4 |
How to use these notes Read these notes after the lecture and before the practical. Section numbers (for example §3.2) are used in the question bank, so you can always find where an answer comes from. Type every code example yourself — do not copy-paste. |
1. What Is Sorting and Why?
Sorting means arranging a list in order: ascending (smallest first) or descending (largest first). (Slide L20-S05)
Sorted list in real life | Order |
|---|---|
UAF admission merit list | descending by aggregate |
PSL points table | descending by points |
Phone contacts | A → Z (ascending) |
Shop price list | cheapest first (ascending) |
Once a list is sorted, important values sit at fixed positions: in ascending order the smallest is a[0], the largest is a[n - 1] and, for odd n, the median (middle value) is a[n / 2].
2. The Swap
Every sort is built from one action: swapping (exchanging) two elements. A third variable temp is needed, just as you need an empty glass to swap the water in two glasses. (Slide L20-S06)
swap.cpp #include <iostream> using namespace std;
int main() { int a = 64, b = 25; int temp = a; // 1. keep a safe a = b; // 2. a gets b b = temp; // 3. b gets the old a cout << "a = " << a << ", b = " << b << endl; return 0; } |
Output a = 25, b = 64 |
swap_bug.cpp #include <iostream> using namespace std;
int main() { int a[2] = {64, 25}; if (a[0] > a[1]) { a[0] = a[1]; // BUG: 64 is lost here a[1] = a[0]; } cout << a[0] << " " << a[1] << endl; return 0; } |
Output — wrong 25 25 |
Without temp, the first assignment overwrites 64 and it is lost for ever.
3. Bubble Sort
3.1 The idea
Compare each pair of neighbours and swap them if they are in the wrong order. After one pass (one full run through the list) the largest value has 'bubbled up' to the end, like an air bubble rising in a glass of cold drink. (Slide L20-S07)
Figure 20.1 – Pass 1 of bubble sort: 64 moves to the end in four swaps (Slide L20-S07)
- Each pass fixes one more value at the end, so the next pass can stop one place earlier.
- n values need n − 1 passes.
3.2 Bubble sort in C++
(Slide L20-S08)
bubble.cpp #include <iostream> using namespace std;
int main() { const int N = 5; int a[N] = {64, 25, 12, 22, 11};
for (int pass = 1; pass < N; pass++) { // N - 1 passes for (int j = 0; j < N - pass; j++) { // compare neighbours if (a[j] > a[j + 1]) { // wrong order? int temp = a[j]; // swap them a[j] = a[j + 1]; a[j + 1] = temp; } } cout << "After pass " << pass << ": "; for (int k = 0; k < N; k++) cout << a[k] << " "; cout << endl; } return 0; } |
Output After pass 1: 25 12 22 11 64 After pass 2: 12 22 11 25 64 After pass 3: 12 11 22 25 64 After pass 4: 11 12 22 25 64 |
- Outer loop: one round per pass (1 to N − 1). Inner loop: compares a[j] and a[j + 1].
- j < N - pass keeps a[j + 1] inside the array and skips the values already in place.
- Comparisons for 5 values: 4 + 3 + 2 + 1 = 10.
3.3 Stopping early with a flag
If a whole pass makes no swap, the list is already sorted, so we can stop (flag pattern, Lecture 14). (Slide L20-S09)
bubble_flag.cpp #include <iostream> using namespace std;
int main() { const int N = 6; int a[N] = {11, 12, 22, 25, 64, 70}; // already sorted int passes = 0;
for (int pass = 1; pass < N; pass++) { bool swapped = false; // flag pattern for (int j = 0; j < N - pass; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; swapped = true; } } passes++; if (!swapped) break; // no swap: list is sorted } cout << "Passes used: " << passes << endl; return 0; } |
Output Passes used: 1 |
Without the flag this already-sorted list of 6 values would still take 5 passes and 15 comparisons. The flag must be reset to false at the start of every pass.
4. Selection Sort
4.1 The idea
Find the smallest value in the unsorted part and swap it into the next place. Repeat for the rest. This is 'minimum with position' from Lecture 18, done once for every place. Real-world: lining students up by height — pick the shortest to stand first, then the shortest of the rest, and so on. (Slide L20-S10)
Figure 20.2 – Selection sort: one smallest value is placed in each pass (Slide L20-S10)
4.2 Selection sort in C++
(Slide L20-S11)
selection.cpp #include <iostream> using namespace std;
int main() { const int N = 5; int a[N] = {64, 25, 12, 22, 11};
for (int i = 0; i < N - 1; i++) { int minPos = i; // smallest so far for (int j = i + 1; j < N; j++) { if (a[j] < a[minPos]) minPos = j; // min with position (L18) } int temp = a[i]; // put it in place i a[i] = a[minPos]; a[minPos] = temp;
cout << "After pass " << i + 1 << ": "; for (int k = 0; k < N; k++) cout << a[k] << " "; cout << endl; } return 0; } |
Output After pass 1: 11 25 12 22 64 After pass 2: 11 12 25 22 64 After pass 3: 11 12 22 25 64 After pass 4: 11 12 22 25 64 |
- minPos starts at i (the first unsorted place) in every pass; the search runs from i + 1.
- Only one swap per pass — at most n − 1 swaps in total.
5. Comparing the Sorts and Sorting in Descending Order
(Slide L20-S12)
Bubble sort | Selection sort | |
|---|---|---|
Idea | swap wrong-order neighbours | pick the smallest of the rest |
Passes (n = 5) | 4 (fewer with the flag) | 4 |
Comparisons (n = 5) | 10 | 10 |
Swaps | up to 10 | at most 4 |
Best for | lists that are almost sorted | when swaps are costly |
Both make n(n − 1) / 2 comparisons in the worst case: 10 for 5 values, 45 for 10 values, 4950 for 100 values — the work grows quickly as the list grows.
To sort descending (largest first), change one comparison: in bubble sort swap when a[j] < a[j + 1]; in selection sort search for the maximum position.
descending.cpp #include <iostream> using namespace std;
int main() { const int N = 6; int runs[N] = {45, 102, 12, 67, 88, 50};
for (int pass = 1; pass < N; pass++) for (int j = 0; j < N - pass; j++) if (runs[j] < runs[j + 1]) { // < gives largest first int temp = runs[j]; runs[j] = runs[j + 1]; runs[j + 1] = temp; }
cout << "Highest first: "; for (int k = 0; k < N; k++) cout << runs[k] << " "; cout << endl; cout << "Top 3: " << runs[0] << ", " << runs[1] << ", " << runs[2] << endl; return 0; } |
Output Highest first: 102 88 67 50 45 12 Top 3: 102, 88, 67 |
6. Common Mistakes
(Slide L20-S14)
Mistake | Result | Fix |
|---|---|---|
Swap without temp | a value is lost (25 25) | temp = a; a = b; b = temp; |
Bubble inner loop j < N | a[j + 1] reads a[N] — out of bounds | j < N − pass |
Too few passes | the last values stay unsorted (e.g. 2 1 3 4 5) | passes 1 to N − 1 |
minPos set once before the outer loop | wrong values are swapped | int minPos = i; inside the outer loop |
Sorting marks but not roll numbers | marks no longer match students | swap both arrays together |
Test cases for sorting Already sorted · reverse order (the worst case) · equal values · a single element. |
7. Word Bank (Key Terms)
Word | Simple meaning |
|---|---|
Sort | Arrange in order |
Ascending / descending | Smallest first / largest first |
Swap | Exchange two values using a temp variable |
Pass | One full run of the inner loop |
Neighbours | Two elements side by side: a[j] and a[j + 1] |
Median | The middle value of a sorted list |
8. Self-Check Questions
1. Bubble sort {5, 1, 4, 2, 8}: what is the array after pass 1?
2. Selection sort {29, 10, 14, 37, 13}: what is the array after pass 1 and after pass 2?
3. How many comparisons does bubble sort (no flag) make for 6 values?
4. Why is a temp variable needed to swap?
5. Which comparison makes bubble sort sort largest first?
6. Why must minPos be set to i inside the outer loop?
Answers: 1 4 2 5 8; 10 29 14 37 13 then 10 13 14 37 29; 15; without it the first value is lost (§2); a[j] < a[j + 1] (§5); each pass searches only the unsorted part from i (§4.2). Homework is on Slide L20-S16.