Python Algorithms: Sorting, Searching, and Knapsack
Classified in Computers
Written on in
English with a size of 3.72 KB
Selection Sort
The Selection Sort algorithm sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning.
array = [45, 2, 23, 76, 7]
for i in range(0, len(array) - 1):
smallest = array[i]
pos = i
for j in range(i + 1, len(array)):
if array[j] < smallest:
smallest = array[j]
pos = j
array[pos] = array[i]
array[i] = smallest
print(array)Insertion Sort
Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time, which is much less efficient on large lists than more advanced algorithms.
array = [35, 7, 18, 30]
for i in range(1, len(array)):
testPosition = i - 1
while True:
if testPosition... Continue reading "Python Algorithms: Sorting, Searching, and Knapsack" »