Skip to content

Commit

Permalink
Add gnome sort (#133)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonWaldherr authored Oct 29, 2024
1 parent 64b7b70 commit ce8a694
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions sorting_algorithms/gnome_sort.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Gnome Sort Function
# Sorts an input vector using the Gnome Sort algorithm.
# Parameters:
# - arr: Input vector to be sorted.
# Returns:
# - Sorted vector.

gnome_sort <- function(arr) {
index <- 1
n <- length(arr)

while (index <= n) {
if (index == 1 || arr[index] >= arr[index - 1]) {
index <- index + 1
} else {
# Swap arr[index] and arr[index - 1]
temp <- arr[index]
arr[index] <- arr[index - 1]
arr[index - 1] <- temp
index <- index - 1
}
}

return(arr)
}

# Example usage:
elements_vec <- c(34, 2, 10, -9)
gnome_sorted_vec <- gnome_sort(elements_vec)
print(gnome_sorted_vec)

0 comments on commit ce8a694

Please sign in to comment.