""" Practice with algorithms - Sorting Below you will find code for the following sorting algorithms: selection sort, insertion sort, and bubble sort """ def selection_sort (array) : for i in range(len(array)) : min = i; # find the smallest element in the unsorted part of the list for j in range(i + 1, len(array)) : if (array[j] < array[min]) : min = j # put the smallest element in its correct position: array[i],array[min] = array[min],array[i] def insertion_sort(array) : for i in range(1,len(array)) : temp = array[i] position = i # shift larger values to the right while (position > 0 and array[position-1] > temp) : array[position] = array[position-1] position-=1 # insert the current item array[position] = temp; def bubble_sort(array) : for position in range(len(array)-1, 0, -1) : for i in range(position) : if (array[i] > array[i+1]) : array[i],array[i+1] = array[i+1],array[i] # an alternative form for the for loops: def bubble_sort2(array): for i in range(len(array)-1) : for j in range(len(array)-1-i) : if array[j] > array[j+1] : array[j], array[j+1] = array[j+1], array[j] # let's run the algorithms: a = [1,3,5,2,4] print a selection_sort(a) print a a = [1,3,5,2,4] print a insertion_sort(a) print a a = [1,3,5,2,4] print a bubble_sort(a) print a