|
| 1 | +# Patience Sort Function |
| 2 | +# Sorts an input vector using the Patience Sort algorithm. |
| 3 | +# Parameters: |
| 4 | +# - arr: Input vector to be sorted. |
| 5 | +# Returns: |
| 6 | +# - Sorted vector. |
| 7 | + |
| 8 | +patience_sort <- function(arr) { |
| 9 | + if (length(arr) == 0) { |
| 10 | + return(arr) |
| 11 | + } |
| 12 | + |
| 13 | + piles <- list() |
| 14 | + |
| 15 | + # Build piles |
| 16 | + for (x in arr) { |
| 17 | + placed <- FALSE |
| 18 | + for (i in seq_along(piles)) { |
| 19 | + if (x < tail(piles[[i]], n=1)) { |
| 20 | + piles[[i]] <- c(piles[[i]], x) |
| 21 | + placed <- TRUE |
| 22 | + break |
| 23 | + } |
| 24 | + } |
| 25 | + if (!placed) { |
| 26 | + piles[[length(piles) + 1]] <- c(x) |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + # Collect sorted elements |
| 31 | + sorted_arr <- c() |
| 32 | + while (length(piles) > 0) { |
| 33 | + # Find the pile with the smallest top element |
| 34 | + min_top <- Inf |
| 35 | + min_index <- -1 |
| 36 | + for (i in seq_along(piles)) { |
| 37 | + if (tail(piles[[i]], n=1) < min_top) { |
| 38 | + min_top <- tail(piles[[i]], n=1) |
| 39 | + min_index <- i |
| 40 | + } |
| 41 | + } |
| 42 | + # Remove the smallest top element and add it to the sorted array |
| 43 | + sorted_arr <- c(sorted_arr, min_top) |
| 44 | + piles[[min_index]] <- head(piles[[min_index]], -1) |
| 45 | + if (length(piles[[min_index]]) == 0) { |
| 46 | + piles[[min_index]] <- NULL |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return(sorted_arr) |
| 51 | +} |
| 52 | + |
| 53 | +# Example usage: |
| 54 | +elements_vec <- c(4, 3, 2, 1) |
| 55 | +patience_sorted_vec <- patience_sort(elements_vec) |
| 56 | +print(patience_sorted_vec) |
0 commit comments