Problem 120 Selection Sort

Back to Problem Solutions forum

Bill Hardwick     2019-05-30 14:05:57

Hi

Can anyone tell me what's wrong with this python solution? It works on the short sample data, but on any of the test data files
I've tried, it ALMOST works (!) with just one or two values wrong. I've added a couple of extra print lines to try to solve
the mystery, and it shows that the sorted array has just one or two values in the wrong order by one place. This tallies
with the fact that the list of index/value pairs I've printed for the swaps in just those error cases are swapping the misplaced
supposedly maximum value in the sub-array with the upper bound (ub) of the sub-array, which is in fact higher - hence
the error. So that's the pattern, but what I don't see is the cause. Help anyone?

with open(r'C:\Users\Bill\Documents\Temp\Data.txt') as f:
    arr = [int(n) for n in f.read().strip().split()]
    ub = len(arr) -1
    for ub in range(len(arr) -1, 0, -1):
        mx = arr.index(max(arr[:ub]))
        print(mx, arr[mx], ub, arr[ub])
        print(mx, end = ' ')
        arr[ub], arr[mx] = arr[mx], arr[ub]
    print('ARRAY\n', arr)

Oh, and I should mention I don't copy the first value of the test data sets when it merely indicates the number of test cases or
items, hence my first line just gets straight on with the array values themselves.

Bill H

Rodion (admin)     2019-05-30 18:12:21
User avatar

Bill, Hi!

I'm not sure, but testing on a very small example of input 1 2 3 it looks like your code on the first pass tries to make 2 and 3. I suppose that in the line

mx = arr.index(max(arr[:ub]))

we may want ub+1?

Bill Hardwick     2019-05-31 08:03:39

Well spotted, Rodion! That did the trick.

I think I got hung up on the fact that it worked OK with the sample data, but not quite with the test data sets. That set me focusing
on potential data pattern issues, and dismissing boundary condition errors in the code sine=ce the only calculation was to subtract
1 from the upper bound.

I'd say wrestling with that one yesterday turned my hair grey - but it's been white for a good few years now, so that would be wrong
too.

Thanks for responding

Please login and solve 5 problems to be able to post at forum