Sorted data is easier to search, read and summarise. Selection sort is one of the simplest sorting methods and is the one used in this unit. This section also answers a question the study material raises: what happens when an array is given to a function?
Selection sort
For an array of n elements, selection sort makes n − 1 passes. Pass i scans the elements from position i to the end, so the total number of comparisons is
(n−1)+(n−2)+⋯+1=2n(n−1)
which grows like n2, written O(n2). A swap of two elements needs a temporary variable: tmp = a[i]; a[i] = a[min_pos]; a[min_pos] = tmp;.
Passing an array to a function
When an array name is used as a function argument, the function does not receive a copy of the elements. It receives the address of the first element. Through that address, the function works on the caller’s original array, so changes it makes are visible to the caller. The function cannot find the size from the array itself, so the size is passed as a second argument.
Two common applications of arrays (Check Your Progress 2): frequency counts, where count[v] records how many times the value v occurs, and tables of data such as marks lists, matrices and lookup tables for searching and sorting.
Key takeaways
Selection sort: for each position, find the smallest remaining element and swap it in.
n − 1 passes and n(n − 1)/2 comparisons, so about n² work.
Swapping needs a temporary variable.
A function receives the address of an array, so it can change the caller’s elements.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Show the array after each pass when {29, 10, 14, 37, 13} is sorted in ascending order by selection sort.
Show worked answer
Pass 1: the smallest of all five is 10; swap with 29 → 10 29 14 37 13. Pass 2: the smallest of 29 14 37 13 is 13; swap with 29 → 10 13 14 37 29. Pass 3: the smallest of 14 37 29 is 14, already in place → 10 13 14 37 29. Pass 4: the smallest of 37 29 is 29; swap with 37 → 10 13 14 29 37. The array is sorted after 4 passes.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/arrays-and-strings/selection-sort-and-passing-arrays-to-functions/ to read this page.