#!/usr/bin/python3
# ===================================================================
# given a random list of values, rearrange the list values into
# high/low pairs. use the initial list; do not create a new list.
#
# example results:
# [ <highest-value>,<lowest-value>,
# <next-highest_value>, <next-lowest,value>,
# <next-high-value>,<next-low-value>,
# ... ]
#
# ===================================================================
# -------------------------------------------------------------------
# ---- given a list and two list indexes, swap the values if one
# ---- value is less than the other value
# ---- make sure the values exist before swapping
# -------------------------------------------------------------------
def swap_values(lst,i,j):
if i < len(lst) and j < len(lst) and i != j and lst[i] < lst[j]:
lst[i],lst[j] = lst[j],lst[i]
# -------------------------------------------------------------------
# ---- rearrainge the list into high/low pairs (in place)
# -------------------------------------------------------------------
def rearrange_list(lst):
# ---- are there enough elements in the list to swap?
if len(lst) < 2:
return
# ---- rearrange the list, there are enough elements in the list
for high_idx in range(0,len(lst)-1,2):
# ---- find highest value
for idx in range(high_idx+1,len(lst)):
swap_values(lst,high_idx,idx)
# ---- find lowest value
for idx in range(high_idx+2,len(lst)):
swap_values(lst,idx,high_idx+1)
# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------
if __name__ == '__main__':
# random lists for testing
testlists = [
[56,21,1,5,87,65,2,10], # even
[87,56,21,1,5,65,10,2], # even
[56,21,1,5,87,65,2], # odd
[1,21,56], # 3 elements
[56,21], # 2 elements
[21,56], # 2 elements
[199], # 1 element
[] # 0 elements
]
for lst in testlists:
print()
print(f'start: {lst}')
rearrange_list(lst)
print(f'final: {lst}')
print()