Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create shell_sort #102

Merged
merged 8 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions sorting_algorithms/bucket_sort.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Bucket Sort Function
# Sorts an input vector using the Bucket Sort algorithm.
# Parameters:
# - arr: Input vector to be sorted.
# Returns:
# - Sorted vector.
bucket_sort <- function(arr) {
if (length(arr) == 0) {
return(arr)
}

# Find the maximum and minimum values in the input vector
max_val <- max(arr)
min_val <- min(arr)

# Create an array of buckets
num_buckets <- max_val - min_val + 1
buckets <- vector("list", length = num_buckets)

# Initialize the buckets
for (i in 1:num_buckets) {
buckets[[i]] <- numeric(0)
}

# Place elements into buckets
for (val in arr) {
bucket_index <- val - min_val + 1
buckets[[bucket_index]] <- c(buckets[[bucket_index]], val)
}

# Sort each bucket (using any sorting algorithm, e.g., Bubble Sort)
sorted_buckets <- lapply(buckets, bubble.sort)

# Concatenate the sorted buckets to obtain the final sorted array
sorted_arr <- unlist(sorted_buckets)

return(sorted_arr)
}

# Example usage:
elements_vec <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
bucket_sorted_vec <- bucket_sort(elements_vec)
print(bucket_sorted_vec)
37 changes: 37 additions & 0 deletions sorting_algorithms/shell_sort.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Function to perform Shell Sort
shellSort <- function(arr) {
n <- length(arr)

# Start with a large gap and reduce it
gap <- n %/% 2 # Initial gap

while (gap > 0) {
for (i in (gap + 1):n) {
# Store the current element to be compared
temp <- arr[i]

# Compare the current element with elements at positions 'i - gap', 'i - 2 * gap', ...
j <- i
while (j > gap && arr[j - gap] > temp) {
arr[j] <- arr[j - gap]
j <- j - gap
}

# Place the current element in its correct position
arr[j] <- temp
}

# Reduce the gap for the next iteration
gap <- gap %/% 2
}

return(arr)
}

# Example usage:
arr <- c(12, 34, 54, 2, 3)
cat("Original Array:", arr, "\n")

# Call the Shell Sort function to sort the array
sortedArr <- shellSort(arr)
cat("Sorted Array:", sortedArr, "\n")