I'm training to be a software developer but I'm afraid some basic Maths has gotten in my way.
We're learning about sorting right now, the first of which is a basic selection sort algorithm. Take the following numbers:
[ 9, 5, 17, 11, 12 ]
It takes the first number and sets it as the minimum number and compares it to everything after it. As 5 is smaller than it, it swaps the two numbers around and moves on. This leaves us with:
[ 5, 9, 17, 11, 12 ]
Next, it takes 5 as the minimum number. If searches the numbers after it and as none are smaller than 5, it stays in position and so on. This leaves us with the same terms:
[ 5, 9, 17, 11, 12 ]
The sort effectively works its way from left to right, leaving the numbers sorted as it goes.
Our lecturer has told us that it is sorted in the following way.
To find the smallest, visit n elements and make 2 visits to perform the swap.
To find the next smallest, visit (n-1) elements and make 2 visits to perform the swap.
To find the last term, visit 2 elements and make 2 visits to perform the swap.
This translates to:
n + 2 + (n-1) + 2 + (n-2) + 2 + ... ... + 2 + 2
I know this equation then simplifies to this:
n2/2 + 5n/2 - 3
However, for the life of me, I cannot see how the top equation translates to this. I know that the formula to find the sum of terms in an arithmetic progression is this:
n/2 [2a + (n-1)d] OR n/2 [a + l] where a = first term d = common difference and l = last term.
Despite using this, I don't get the right answer. Could somebody please walk me through, STEP BY STEP!!, as to how I get to the answer?
Kind regards and many thanks in advance.
Edit: Wanted to add that I posted this in the pre-university forum as I remember studying this at A Level - just can't remember the outcome!!


LinkBack URL
About LinkBacks


