-
-
Notifications
You must be signed in to change notification settings - Fork 298
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
64b7b70
commit ce8a694
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |