How it works
Sorts by repeatedly flipping sub-arrays, like arranging pancakes by size. Only uses a "flip" operation (reversing a prefix of the array).
Implementation
function pancakeSort(arr) { function flip(end) { let l = 0, r = end; while (l < r) { [arr[l], arr[r]] = [arr[r], arr[l]]; l++; r--; } } for (let size = arr.length; size > 1; size--) { let maxIdx = 0; for (let i = 1; i < size; i++) if (arr[i] > arr[maxIdx]) maxIdx = i; if (maxIdx !== size - 1) { if (maxIdx > 0) flip(maxIdx); flip(size - 1); } } }
def pancake_sort(arr): def flip(end): l, r = 0, end while l < r: arr[l], arr[r] = arr[r], arr[l] l += 1; r -= 1 for size in range(len(arr), 1, -1): max_idx = max(range(size), key=lambda i: arr[i]) if max_idx != size - 1: if max_idx > 0: flip(max_idx) flip(size - 1)
void pancakeSort(vector<int>& arr) { auto flip = [&](int end) { int l = 0, r = end; while (l < r) swap(arr[l++], arr[r--]); }; for (int size = arr.size(); size > 1; size--) { int maxIdx = max_element(arr.begin(), arr.begin()+size) - arr.begin(); if (maxIdx != size-1) { if (maxIdx > 0) flip(maxIdx); flip(size-1); } } }
void PancakeSort(int[] arr) { void Flip(int end) { int l = 0, r = end; while (l < r) { (arr[l], arr[r]) = (arr[r], arr[l]); l++; r--; } } for (int size = arr.Length; size > 1; size--) { int maxIdx = 0; for (int i = 1; i < size; i++) if (arr[i] > arr[maxIdx]) maxIdx = i; if (maxIdx != size-1) { if (maxIdx > 0) Flip(maxIdx); Flip(size-1); } } }
void flip(int arr[], int end) { int l = 0, r = end; while (l < r) { int t = arr[l]; arr[l] = arr[r]; arr[r] = t; l++; r--; } } void pancakeSort(int arr[], int n) { for (int size = n; size > 1; size--) { int maxIdx = 0; for (int i = 1; i < size; i++) if (arr[i] > arr[maxIdx]) maxIdx = i; if (maxIdx != size-1) { if (maxIdx > 0) flip(arr, maxIdx); flip(arr, size-1); } } }