Python Tutorial

Wednesday, April 24, 2013

Selection sort in python

Selection sort python code.

def get_index_of_smallest(A, i):
    index_of_smallest = i
    for j in range(i+1, len(A)):
        if A[index_of_smallest]>A[j]:
            index_of_smallest = j;
    return index_of_smallest


def selection_sort(A):
    for i in range (0, len(A)):
        index_of_smallest = get_index_of_smallest(A,i)
        A[index_of_smallest], A[i] = A[i], A[index_of_smallest]

if __name__=="__main__":
    A = [7,3,5,2]
    print A
    selection_sort(A)
    print A

Output:
[7, 3, 5, 2]
[2, 3, 5, 7]

0 comments:

Post a Comment