Pancake sorts a slice using flip operations, where flip refers to the idea of reversing the slice from index `0` to `i`.
(arr []T)
| 6 | // where flip refers to the idea of reversing the |
| 7 | // slice from index `0` to `i`. |
| 8 | func Pancake[T constraints.Ordered](arr []T) []T { |
| 9 | // early return if the array too small |
| 10 | if len(arr) <= 1 { |
| 11 | return arr |
| 12 | } |
| 13 | |
| 14 | // start from the end of the array |
| 15 | for i := len(arr) - 1; i > 0; i-- { |
| 16 | // find the index of the maximum element in arr |
| 17 | max := 0 |
| 18 | for j := 1; j <= i; j++ { |
| 19 | if arr[j] > arr[max] { |
| 20 | max = j |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | // if the maximum element is not at the end of the array |
| 25 | if max != i { |
| 26 | // flip the maximum element to the beginning of the array |
| 27 | arr = flip(arr, max) |
| 28 | |
| 29 | // flip the maximum element to the end of the array by flipping the whole array |
| 30 | arr = flip(arr, i) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | return arr |
| 35 | } |
| 36 | |
| 37 | // flip reverses the input slice from `0` to `i`. |
| 38 | func flip[T constraints.Ordered](arr []T, i int) []T { |