8000 Add binary_insertion_sort.r (#95) · TheAlgorithms/R@d73ef9d · GitHub
[go: up one dir, main page]

Skip to content

Commit d73ef9d

Browse files
authored
Add binary_insertion_sort.r (#95)
1 parent bc04a42 commit d73ef9d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Binary Insertion Sort Function
2+
# Sorts an input vector using the Binary Insertion Sort algorithm.
3+
# Parameters:
4+
# - arr: Input vector to be sorted.
5+
# Returns:
6+
# - Sorted vector.
7+
binary_insertion_sort <- function(arr) {
8+
# Loop through the input vector starting from the second element.
9+
for (i in 2:length(arr)) {
10+
# Store the current element in a variable.
11+
key <- arr[i]
12+
# Initialize left and right pointers for binary search.
13+
left <- 1
14+
right <- i - 1
15+
16+
# Binary search to find the correct position to insert the key.
17+
while (left <= right) {
18+
mid <- left + (right - left) %/% 2
19+
20+
if (key < arr[mid]) {
21+
right <- mid - 1
22+
} else {
23+
left <- mid + 1
24+
}
25+
}
26+
27+
# Shift elements to the right to make space for the key.
28+
for (j in i: (left + 1)) {
29+
arr[j] <- arr[j - 1]
30+
}
31+
32+
# Insert the key into its correct position.
33+
arr[left] <- key
34+
}
35+
36+
# Return the sorted vector.
37+
return(arr)
38+
}
39+
40+
# Example usage:
41+
elements_vec <- c(64, 34, 25, 12, 22, 11, 90)
42+
sorted_vec <- binary_insertion_sort(elements_vec)
43+
print(sorted_vec)

0 commit comments

Comments
 (0)
0