Я создал работающую Python программу для демонстрации алгоритма, но я думаю, что он так же удобен для чтения, как и псевдокод для всех (я сделал код очень простым). Решение довольно жестокое, но, похоже, работает. Также есть большой потенциал для дальнейшей оптимизации. Я помещаю описания в комментарии:
x = [15, 12, 3, 2, 13]
def putend():
x.append(x.pop(0))
def swap():
x[0], x[1] = x[1], x[0]
def doubleswap():
x[0], x[1], x[2] = x[1], x[2], x[0]
def put_smallest_back():
smallest = min(x[0], x[1], x[2])
if x[2] == smallest:
# Move smallest to x[1]
doubleswap()
if x[1] == smallest:
# Move smallest to x[0]
swap()
putend()
# Put back two smallest values of four to make sure two largest are in front
put_smallest_back()
put_smallest_back()
# Now two largest values are in three accessible cells
# Find and put back second largest
largest = max(x[0], x[1], x[2])
smallest = min(x[0], x[1], x[2])
if x[2] != largest and x[2] != smallest:
doubleswap()
if x[1] != largest and x[1] != smallest:
swap()
putend()
# Find and put back largest
# Largest is in x[0] or x[1]
if x[1] == largest:
swap()
# Largest is in x[0]
putend()
# Two largest values are sorted
# Time to sort x[2]
if x[0] > x[1] and x[0] > x[2]:
doubleswap()
elif x[1] > x[0] and x[1] > x[2]:
swap()
doubleswap()
# Last step, sort x[0] and x[1]
if x[0] > x[1]:
swap()
# Voilla!
print(x)
Я использовал min()
и max()
функции без их определения, но их реализация тривиальна, особенно они всегда работают с первыми тремя элементами коллекции.