If performance is important we may use this algorithm which will be of O(n)
function swap!(a)
i_max = argmax(a)
i_second = argmin(a)
d = a[i_max] - a[i_second] # make this difference minimum to get the second max value
for i in 1:length(a)
diff = a[i_max] - a[i]
if 0 < diff < d
i_second = i
d = diff
end
end
a[i_max], a[i_second] = a[i_second], a[i_max]
return a
end
swap!(a)