We continue our discussion of stack and vector this lesson and introduce some other concepts along the way.

Sorting

Sorting refers to arranging elements in a particular order (usually ascending). For example, $[4, 2, 5, 1, 3]$ is sorted as $[1, 2, 3, 4, 5]$. There are many sorting algorithms, but those we will discuss eventually are: bubble sort, insertion sort, selection sort, merge sort, and quick sort.

Selection Sort

We initialize an empty vector that we will keep as sorted. Then, we process the unsorted elements $x$ one by one: we insert $x$ into a position such that the vector remains sorted. The position we want is the index of the first element that is larger than $x$.

Branching Statements

Break

The break statement is used to exit a loop (including for and while). For example:

for (int i = 0; i < 5; i++) {
    if (i == 3) break;
    cout << i << "\n";
}

This code will print:

0
1
2

For nested loops, the break statement only exits the inner loop but not the outer loop.

Continue

The continue statement is used to skip the current iteration. For example:

for (int i = 0; i < 5; i++) {
    if (i == 3) continue;
    cout << i << "\n";
}

This code will print:

0
1
2
4

Authored by s16f22