Skip to content

Commit 5da148e

Browse files
Add strand sort (#136)
1 parent ad2f096 commit 5da148e

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

sorting_algorithms/strand_sort.r

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Strand Sort Function
2+
# Sorts an input vector using the Strand Sort algorithm.
3+
# Parameters:
4+
# - arr: Input vector to be sorted.
5+
# Returns:
6+
# - Sorted vector.
7+
8+
strand_sort <- function(arr) {
9+
if (length(arr) <= 1) {
10+
return(arr)
11+
}
12+
13+
output <- c()
14+
15+
while (length(arr) > 0) {
16+
sublist <- c(arr[1])
17+
arr <- arr[-1]
18+
i <- 1
19+
while (i <= length(arr)) {
20+
if (arr[i] >= tail(sublist, n=1)) {
21+
sublist <- c(sublist, arr[i])
22+
arr <- arr[-i]
23+
} else {
24+
i <- i + 1
25+
}
26+
}
27+
output <- merge_sorted_lists(output, sublist)
28+
}
29+
30+
return(output)
31+
}
32+
33+
# Helper function to merge two sorted lists
34+
merge_sorted_lists <- function(list1, list2) {
35+
result <- c()
36+
i <- 1
37+
j <- 1
38+
39+
while (i <= length(list1) && j <= length(list2)) {
40+
if (list1[i] <= list2[j]) {
41+
result <- c(result, list1[i])
42+
i <- i + 1
43+
} else {
44+
result <- c(result, list2[j])
45+
j <- j + 1
46+
}
47+
}
48+
49+
if (i <= length(list1)) {
50+
result <- c(result, list1[i:length(list1)])
51+
}
52+
53+
if (j <= length(list2)) {
54+
result <- c(result, list2[j:length(list2)])
55+
}
56+
57+
return(result)
58+
}
59+
60+
# Example usage:
61+
elements_vec <- c(4, 2, 5, 3, 1)
62+
strand_sorted_vec <- strand_sort(elements_vec)
63+
print(strand_sorted_vec)

0 commit comments

Comments
 (0)