Sorting Searching Algorithms Notes
Sorting Searching Algorithms Notes
Swapping Elements
Selection Sort
Bubble Sort
Notice in line 2 that we only loop I to the
1 procedure BUBBLE_SORT(XS, N) second last position of the array; this is
2 loop I from 0 to N - 2 because we are comparing each element
3 loop J from 0 to N - 2 - I to the element on its right and we don't
4 if XS[J] > XS[J + 1] then want to go out of bounds.
5 SWAP(XS, J, J + 1)
Also notice in line 3 that we subtract I
6 end if
from the upper bound of J; this is because
7 end loop we know that the elements after this point
8 end loop are already sorted.
9 end procedure
Insertion Sort
Notice in line 2 that we start from index 1
1 procedure INSERTION_SORT(XS, N)
so that we can safely compare the
2 loop I from 1 to N - 1 previous element without going out of
3 J = I bounds.
4 loop while J > 0 and XS[J - 1] > XS[J]
5 SWAP(XS, J, J - 1) Also notice in line 4 that we only continue
6 J = J - 1 swapping elements while the previous
element is greater than the element we
7 end loop
are inserting; this is because we know that
8 end loop all elements after that are already sorted.
9 end procedure
Basic Searching Algorithms: Example Designs
Binary Search