Selection sort

In this tutorial I am planning to explain about the selection sort.

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

Lets look into an example:

input list:

[8, 7, 6, 5, 4, 3, 2, 1]

While sorting:

[8, 7, 6, 5, 4, 3, 2, 1]

[ 1, 7, 6, 5, 4, 3, 2, 8]

[ 1, 2, 6, 5, 4, 3, 7, 8]

[ 1, 2, 3, 5, 4, 6, 7, 8]

[ 1, 2, 3, 4, 5, 6, 7, 8]

[ 1, 2, 3, 4, 5, 6, 7, 8]

[ 1, 2, 3, 4, 5, 6, 7, 8]

[ 1, 2, 3, 4, 5, 6, 7, 8]

Sorted list:

[ 1, 2, 3, 4, 5, 6, 7, 8]

This the corresponding python code:

# /usr/bin/python
# A program to do selection sort

def selection_sort(inp_list):
    '''The selection sort function'''

    for i in range (len(inp_list)): # C*(n+1), where n is the length of the input list
        iMin = i                    # C*n
        for j in range(i+1, len(inp_list)): # C*n*\latex{\sum\limits_{j=i+1}^n j}
            if inp_list[j] < inp_list[iMin]: # C*n*\latex{\sum\limits_{j=i+1}^n j} 
                iMin = j                     # C*n*\latex{\sum\limits_{j=i+1}^n j}   

        if iMin != i:                        # C*n
            temp = inp_list[i]               # C*n
            inp_list[i] = inp_list[iMin]     # C*n
            inp_list[iMin] = temp            # C*n
    return inp_list                          # C*1

def main():
    '''Main function'''

    inp =[]
    s = int(raw_input('How many elements would you like to enter: '))
    for x in range(s):
        inp.append(int(raw_input('Enter element #' + `x+1` + ': ')))
    print "Input list: ", inp
    output_list = selection_sort(inp) 
    print "Sorted list: ", output_list

if __name__ == "__main__":
    main()

Best case (if the list is already sorted): O(n)
Worst case (if the list is sorted in descending order): C*n*\latex{\sum\limits_{j=0}^n j} = O(n^2)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s