954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Learning to understand selection sort

0
By Tony Veijalainen on Sep 13th, 2011 2:39 pm

By coding algorithm and using some liberal prints with small set of data, you can learn to understand the basic algorithms better than just reading about them.

Here simple selection sort.

""" demonstrating simple selection sort with prints"""

data = [64, 25, 12, 25, 22, 11, 62]

for current in range(len(data)-1):
    min_value_index = current
    print('Sorted: %s, Checking: %s' % (data[:current],data[current:]))
    for index, d in enumerate(data[current:], current):
        if data[min_value_index] > d:
            min_value_index = index
    if min_value_index != current:
        data[current], data[min_value_index] = data[min_value_index], data[current]
    else:
        print('No swap needed')

print('\nReady result:')
print(data)

OK, if you put one print more you can find a stupid thing I do. Up vote for first one to spot it.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 
""" demonstrating simple selection sort with prints"""

data = [64, 25, 12, 25, 22, 11, 62]

for current in range(len(data)-1):
    min_value_index = current
    print('Sorted: %s, Checking: %s' % (data[:current],data[current:]))
    # min_value_index = current, does not need to check that -> + 1
    for index, d in enumerate(data[current + 1:], current + 1):
        #print(index, min_value_index)
        if data[min_value_index] > d:
            min_value_index = index
    if min_value_index != current:
        data[current], data[min_value_index] = data[min_value_index], data[current]
    else:
        print('No swap needed')

print('\nReady result:')
print(data)
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: