34 56 14 20 77 51 93 30 15 52
14 56 34 20 77 51 93 30 15 52
14 15 34 20 77 51 93 30 56 52
14 15 20 34 77 51 93 30 56 52
14 15 20 30 34 51 52 56 77 93
Note: The last two lines of source code in this example have been modified from the print book so you can execute the example inside the notebook.
selection_sort
¶len(data) - 1
timessmallest
stores the index of the smallest element in the remaining arraysmallest
to the current index index1
smallest
smallest
will contain the index of the smallest element in the remaining array# selectionsort.py
"""Sorting an array with selection sort."""
import numpy as np
from ch11utilities import print_pass
def selection_sort(data):
"""Sort array using selection sort."""
# loop over len(data) - 1 elements
for index1 in range(len(data) - 1):
smallest = index1 # first index of remaining array
# loop to find index of smallest element
for index2 in range(index1 + 1, len(data)):
if data[index2] < data[smallest]:
smallest = index2
# swap smallest element into position
data[smallest], data[index1] = data[index1], data[smallest]
print_pass(data, index1 + 1, smallest)
main
¶def main():
data = np.array([34, 56, 14, 20, 77, 51, 93, 30, 15, 52])
print(f'Unsorted array: {data}\n')
selection_sort(data)
print(f'\nSorted array: {data}\n')
# call main to run the sort
main()
# ch11utilities.py
"""Utility function for printing a pass of the
insertion_sort and selection_sort algorithms"""
def print_pass(data, pass_number, index):
"""Print a pass of the algorithm."""
label = f'after pass {pass_number}: '
print(label, end='')
# output elements up to selected item
print(' '.join(str(d) for d in data[:index]),
end=' ' if index != 0 else '')
print(f'{data[index]}* ', end='') # indicate swap with *
# output rest of elements
print(' '.join(str(d) for d in data[index + 1:len(data)]))
# underline elements that are sorted after this pass_number
print(f'{" " * len(label)}{"-- " * pass_number}')
©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.