Skip to content
Closed
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
37 changes: 14 additions & 23 deletions sorting_algorithms/cocktail_sort.r
Original file line number Diff line number Diff line change
@@ -1,56 +1,47 @@
cocktailSort <- function(arr) {
# Cocktail Sort in R
cocktail.sort <- function(arr) {
n <- length(arr)
swapped <- TRUE
beg <- 1
start <- 1
end <- n - 1

while (swapped) {
swapped <- FALSE

# Forward pass (left to right)
for (i in seq(beg, end)) {
# Forward pass
for (i in seq(start, 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
}
if (!swapped) break

swapped <- FALSE
end <- end - 1

# Backward pass (right to left)
for (i in seq(end, beg, by = -1)) {
# Backward pass
for (i in seq(end, start, 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
start <- start + 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
# Example usage
unsorted.array <- c(38, 27, 43, 3, 9, 82, 10)
cat("Unsorted Array:", unsorted.array, "\n")

sorted.array <- cocktail.sort(unsorted.array)
cat("Sorted Array: ", sorted.array, "\n")
20 changes: 20 additions & 0 deletions string_manipulation/unique.letters.count.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Ask for user input
input.string <- readline(prompt = "Enter a string: ")

# Convert to lowercase and remove non-letter characters
clean.string <- tolower(gsub("[^a-z]", "", input.string))

# Split string into individual letters
letters.vec <- strsplit(clean.string, "")[[1]]

# Get unique letters
unique.letters <- unique(letters.vec)

# Count occurrences of each unique letter
letter.counts <- table(letters.vec)

# Display results
cat("Unique letters and their counts:\n")
for (letter in unique.letters) {
cat(letter, ":", letter.counts[letter], "\n")
}