Skip to content

Commit ce8a694

Browse files
Add gnome sort (#133)
1 parent 64b7b70 commit ce8a694

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

sorting_algorithms/gnome_sort.r

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Gnome Sort Function
2+
# Sorts an input vector using the Gnome Sort algorithm.
3+
# Parameters:
4+
# - arr: Input vector to be sorted.
5+
# Returns:
6+
# - Sorted vector.
7+
8+
gnome_sort <- function(arr) {
9+
index <- 1
10+
n <- length(arr)
11+
12+
while (index <= n) {
13+
if (index == 1 || arr[index] >= arr[index - 1]) {
14+
index <- index + 1
15+
} else {
16+
# Swap arr[index] and arr[index - 1]
17+
temp <- arr[index]
18+
arr[index] <- arr[index - 1]
19+
arr[index - 1] <- temp
20+
index <- index - 1
21+
}
22+
}
23+
24+
return(arr)
25+
}
26+
27+
# Example usage:
28+
elements_vec <- c(34, 2, 10, -9)
29+
gnome_sorted_vec <- gnome_sort(elements_vec)
30+
print(gnome_sorted_vec)

0 commit comments

Comments
 (0)