Analysis of Selection Sort
We'll cover the following
Selection sort loops over indices in the array; for each index, selection sort calls indexOfMinimum
and swap. If the length of the array is
Since each execution of the body of the loop runs two lines of code, you might think that indexOfMinimum
and swap
are functions: when either is called, some lines of code are executed.
How many lines of code are executed by a single call to swap
? In the usual implementation, it's three lines, so that each call to swap takes constant time.
How many lines of code are executed by a single call to indexOfMinimum
? We have to account for the loop inside indexOfMinimum
. How many times does this loop execute in a given call to indexOfMinimum
? It depends on the size of the subarray that it's iterating over. If the subarray is the whole array (as it is on the first step), the loop body runs
In the first call of
indexOfMinimum
, it has to look at every value in the array, and so the loop body inindexOfMinimum
runs 8 times.In the second call of
indexOfMinimum
, it has to look at every value in the subarray from indicesto , and so the loop body in indexOfMinimum
runs 7 times.In the third call, it looks at the subarray from indices
to ; the loop body runs 6 times. In the fourth call, the subarray from indices
to ; the loop body runs 5 times. …
In the eighth and final call of
indexOfMimimum
, the loop body runs just 1 time.
If we total up the number of times the loop body of indexOfMinimum
runs, we get 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 36 times.
Side note: Computing summations from 1 to n
How do you compute the sum
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy