MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Pancake

Function Pancake

sort/pancakesort.go:8–35  ·  view source on GitHub ↗

Pancake sorts a slice using flip operations, where flip refers to the idea of reversing the slice from index `0` to `i`.

(arr []T)

Source from the content-addressed store, hash-verified

6// where flip refers to the idea of reversing the
7// slice from index `0` to `i`.
8func 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`.
38func flip[T constraints.Ordered](arr []T, i int) []T {

Callers

nothing calls this directly

Calls 1

flipFunction · 0.85

Tested by

no test coverage detected