-
-
Notifications
You must be signed in to change notification settings - Fork 302
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
Showing
1 changed file
with
37 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,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") |