Advertisement
Talilo

Selection_sort.py

Mar 16th, 2023 (edited)
525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.62 KB | None | 0 0
  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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement