fork download
  1. # Selection sort in Python
  2.  
  3.  
  4. def selectionSort(array, size):
  5.  
  6. for step in range(size):
  7. min_idx = step
  8.  
  9. for i in range(step + 1, size):
  10.  
  11. # to sort in descending order, change > to < in this line
  12. # select the minimum element in each loop
  13. if array[i] < array[min_idx]:
  14. min_idx = i
  15.  
  16. # put min at the correct position
  17. (array[step], array[min_idx]) = (array[min_idx], array[step])
  18.  
  19.  
  20. data = [-2, 45, 0, 11, -9]
  21. size = len(data)
  22. selectionSort(data, size)
  23. print('Sorted Array in Ascending Order:')
  24. print(data)
Success #stdin #stdout 0.04s 9664KB
stdin
Standard input is empty
stdout
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]