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 cocktail_sort.r #114

Merged
merged 1 commit into from
Oct 14, 2023
Merged
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
56 changes: 56 additions & 0 deletions sorting_algorithms/cocktail_sort.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
cocktailSort <- function(arr) {
n <- length(arr)
swapped <- TRUE
beg <- 1
end <- n - 1

while (swapped) {
swapped <- FALSE

# Forward pass (left to right)
for (i in seq(beg, end)) {
if (arr[i] > arr[i + 1]) {
# Swap arr[i] and arr[i + 1]
temp <- arr[i]
arr[i] <- arr[i + 1]
arr[i + 1] <- temp
swapped <- TRUE
}
}

# If no swaps occurred in the forward pass, the array is sorted
if (!swapped) {
break
}

swapped <- FALSE
end <- end - 1

# Backward pass (right to left)
for (i in seq(end, beg, by = -1)) {
if (arr[i] > arr[i + 1]) {
# Swap arr[i] and arr[i + 1]
temp <- arr[i]
arr[i] <- arr[i + 1]
arr[i + 1] <- temp
swapped <- TRUE
}
}

beg <- beg + 1
}

return(arr)
}

# Example Usage
unsorted_array <- c(38, 27, 43, 3, 9, 82, 10)
cat("Unsorted Array: ", unsorted_array, "\n")

# Call the Cocktail Sort function to sort the array
sorted_array <- cocktailSort(unsorted_array)

cat("Sorted Array: ", sorted_array, "\n")

# Example: The 'unsorted_array' is sorted using Cocktail Sort