How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the F# programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the F# programming language
Table of Contents
Problem Statement
Sort an array of integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the F# programming language
Source code in the fsharp programming language
open System
let show data = data |> Array.iter (printf "%d ") ; printfn ""
let split (data: int[]) pos = data.[0..pos], data.[(pos+1)..]
let flip items pos =
let lower, upper = split items pos
Array.append (Array.rev lower) upper
let pancakeSort items =
let rec loop data limit =
if limit <= 0 then data
else
let lower, upper = split data limit
let indexOfMax = lower |> Array.findIndex ((=) (Array.max lower))
let partialSort = Array.append (flip lower indexOfMax |> Array.rev) upper
loop partialSort (limit-1)
loop items ((Array.length items)-1)
You may also check:How to resolve the algorithm Sum of squares step by step in the GAP programming language
You may also check:How to resolve the algorithm Word wrap step by step in the PureBasic programming language
You may also check:How to resolve the algorithm First-class functions/Use numbers analogously step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Loops/While step by step in the AWK programming language
You may also check:How to resolve the algorithm Dice game probabilities step by step in the C programming language