Wednesday, July 22, 2015

Selection Sort - using Python

Selection sort is also one of the basic sort algorithms and run in quadratic time O(n^2) same as Insertion sort.  The Selection sort is better than Insertion sort in terms of space complexity but has slower  than insertion sort in terms of time complexity.

Here we do not swap numbers after every comparison; rather we find the smallerst/largest numbers, save it in a temporary variable and replace it with the leftmost element in right array. In result we get sorted array on left hand side.


Given an unsorted list the algorithm finds the smallest element and swap it with first element. Then it searches for smallest element in list excluding the 1st element  and so on till the list got sorted finally.

Below are the differences between Selection sort and Insertion sort 


__author__ = 'Dharmjit'
def selection_sort(list):
    for index in range(0, len(list)):
        iSmall = index
        for i in range(index,len(list)):
            if list[iSmall] > list[i]:
                iSmall = i
        list[index], list[iSmall] = list[iSmall], list[index]
    return list

if __name__ == '__main__':

No comments :

Post a Comment

There was an error in this gadget