R Program to Implement Bucket Sort

R Program to Implement Bucket Sort

Bucket Sort is a simple and practical sorting algorithm that works by dividing data into smaller groups called buckets, sorting each bucket, and then combining everything back together. Instead of comparing every number with every other number, Bucket Sort focuses on distributing values into ranges. This makes the algorithm easy to understand and very effective when the data is evenly spread. For beginners learning R programming, Bucket Sort is a friendly way to see how breaking a problem into smaller parts can make sorting faster and cleaner.

Learn C Programming For Free on Windows

A beginner-friendly course that teaches real C programming using a Windows compiler. Learn arrays, pointers, functions, and file handling step by step with practical lessons.

Start Learning C Programming

Bucket Sort is commonly used in real-life situations like sorting exam scores, percentages, or any data that falls within a known range. In places like Nigeria or Zambia, where R is often used for data analysis and statistics, understanding Bucket Sort can be very useful. It also helps beginners build confidence with arrays, loops, and simple logic, which are important foundations in programming.

Program 1: Basic Bucket Sort using loops

This program shows the most straightforward way to implement Bucket Sort in R using loops. It works well for positive numbers that are evenly distributed between 0 and 1. The data is predefined so you can run it immediately.

bucket_sort <- function(arr, bucket_count = 5) {

  buckets <- vector("list", bucket_count)

  for (num in arr) {
    index <- floor(num * bucket_count) + 1
    buckets[[index]] <- c(buckets[[index]], num)
  }

  result <- c()

  for (bucket in buckets) {

    if (length(bucket) > 0) {
      result <- c(result, sort(bucket))
    }

  }

  return(result)

}

data <- c(0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51)
print(bucket_sort(data))

This program places each number into a bucket based on its value and then sorts each bucket using R’s built-in sort function. Beginners can think of this like placing students into classrooms based on age ranges and then arranging each class properly. This approach is useful when you know the range of values in advance.

Program 2: Bucket Sort with dynamic bucket size

This version calculates bucket ranges automatically based on the data. It is helpful when you do not know the exact spread of values beforehand. The logic is still simple and beginner-friendly.

bucket_sort_dynamic <- function(arr) {

  min_val <- min(arr)
  max_val <- max(arr)
  bucket_count <- length(arr)

  buckets <- vector("list", bucket_count)

  for (num in arr) {
    index <- floor((num - min_val) / (max_val - min_val + 1) * bucket_count) + 1
    buckets[[index]] <- c(buckets[[index]], num)
  }

  result <- c()

  for (bucket in buckets) {

    if (length(bucket) > 0) {
      result <- c(result, sort(bucket))
    }

  }

  return(result)

}

data <- c(29, 25, 3, 49, 9, 37, 21, 43)
print(bucket_sort_dynamic(data))

Here, the algorithm adapts to the input values by spreading them evenly across buckets. This makes the program more flexible and closer to real-world use cases. Beginners can learn how formulas help control data distribution in sorting algorithms.

Program 3: Bucket Sort using helper functions

This program separates the bucket logic into smaller helper functions. It follows a traditional programming style that values clarity and readability.

insert_bucket <- function(bucket, value) {
  c(bucket, value)
}

bucket_sort_helpers <- function(arr) {

  bucket_count <- 5
  buckets <- vector("list", bucket_count)

  for (num in arr) {

    index <- floor(num / 10) + 1
    buckets[[index]] <- insert_bucket(buckets[[index]], num)

  }

  result <- c()

  for (bucket in buckets) {

    if (length(bucket) > 0) {
      result <- c(result, sort(bucket))
    }

  }

  return(result)

}

data <- c(12, 45, 33, 27, 8, 19, 41)
print(bucket_sort_helpers(data))

By using helper functions, this program becomes easier to read and maintain. Beginners can focus on one idea at a time, which is a traditional and effective way of learning programming. This style also prepares learners for writing larger R programs later.

Program 4: Bucket Sort using while and for loops

This version mixes while and for loops to show that the same algorithm can be written in different ways. It helps learners feel comfortable experimenting with loop structures.

bucket_sort_mixed <- function(arr) {

  bucket_count <- 4
  buckets <- vector("list", bucket_count)

  i <- 1

  while (i <= length(arr)) {

    index <- floor(arr[i] / 25) + 1
    buckets[[index]] <- c(buckets[[index]], arr[i])
    i <- i + 1

  }

  result <- c()

  for (b in buckets) {

    if (length(b) > 0) {
      result <- c(result, sort(b))
    }

  }

  return(result)

}

data <- c(10, 70, 30, 90, 40, 20, 80)
print(bucket_sort_mixed(data))

This program shows that logic matters more than syntax style. Beginners learn that as long as the idea is correct, there are many valid ways to write code. This builds confidence and encourages exploration.

Program 5: Bucket Sort with manual sorting inside buckets

In this example, each bucket is sorted manually instead of using the built-in sort function. This helps beginners understand what happens inside each bucket.

# Bubble sort for small arrays
manual_sort <- function(arr) {

  if (length(arr) < 2) return(arr)  # safe for empty or 1-element arrays

  n <- length(arr)

  for (i in 1:(n-1)) {

    for (j in 1:(n-i)) {

      if (arr[j] > arr[j+1]) {
        temp <- arr[j]
        arr[j] <- arr[j+1]
        arr[j+1] <- temp
      }

    }

  }

  arr

}

# Bucket sort using manual_sort
bucket_sort_manual <- function(arr, bucket_count = 5) {

  if (length(arr) == 0) return(arr)

  max_val <- max(arr)
  min_val <- min(arr)
  range_val <- max_val - min_val + 1

  # Initialize buckets as numeric vectors
  buckets <- vector("list", bucket_count)

  for (i in 1:bucket_count) buckets[[i]] <- numeric(0)

  # Assign numbers to buckets
  for (num in arr) {

    index <- floor((num - min_val) / range_val * bucket_count) + 1

    if (index > bucket_count) index <- bucket_count
    buckets[[index]] <- append(buckets[[index]], num)

  }

  # Sort each bucket and combine
  result <- numeric(0)

  for (bucket in buckets) {

    if (length(bucket) > 0) {
      result <- append(result, manual_sort(bucket))
    }

  }

  result

}

# Test
data <- c(34, 12, 25, 9, 18, 41, 7)
print(bucket_sort_manual(data))

This approach is slower but very educational. It helps beginners see how Bucket Sort often relies on another sorting method inside each bucket. Understanding this makes the overall algorithm feel less magical and more logical.

Program 6: Bucket Sort using recursion for bucket processing

This version uses recursion to process buckets one by one. While Bucket Sort is not naturally recursive, this example helps learners practice recursive thinking.

process_buckets <- function(buckets, index = 1, result = c()) {

  if (index > length(buckets)) {
    return(result)
  }

  if (length(buckets[[index]]) > 0) {
    result <- c(result, sort(buckets[[index]]))
  }

  process_buckets(buckets, index + 1, result)

}

bucket_sort_recursive <- function(arr) {

  bucket_count <- 4
  buckets <- vector("list", bucket_count)

  for (num in arr) {
    index <- floor(num / 25) + 1
    buckets[[index]] <- c(buckets[[index]], num)
  }

  process_buckets(buckets)

}

data <- c(15, 60, 35, 90, 45, 20)
print(bucket_sort_recursive(data))

This program shows that recursion can be applied even when it is not the most obvious choice. Beginners gain experience with function calls and stopping conditions, which are important concepts in R.

Program 7: Bucket Sort for large integer ranges

This example focuses on handling larger numbers by increasing bucket ranges. It is useful when working with bigger datasets.

bucket_sort_large <- function(arr) {

  bucket_count <- 10
  buckets <- vector("list", bucket_count)

  for (num in arr) {
    index <- floor(num / 100) + 1
    buckets[[index]] <- c(buckets[[index]], num)
  }

  result <- c()

  for (bucket in buckets) {

    if (length(bucket) > 0) {
      result <- c(result, sort(bucket))
    }

  }

  return(result)

}

data <- c(120, 450, 230, 890, 510, 760)
print(bucket_sort_large(data))

This program helps beginners understand how bucket ranges affect performance. Choosing good ranges is an important skill when applying Bucket Sort to real data.

Program 8: Bucket Sort with custom bucket count

This version allows you to control how many buckets are used. It shows how small changes can make an algorithm more flexible.

bucket_sort_custom <- function(arr, bucket_count) {

  buckets <- vector("list", bucket_count)

  for (num in arr) {
    index <- floor(num / (100 / bucket_count)) + 1
    buckets[[index]] <- c(buckets[[index]], num)
  }

  result <- c()

  for (bucket in buckets) {

    if (length(bucket) > 0) {
      result <- c(result, sort(bucket))
    }

  }

  return(result)

}

data <- c(10, 55, 70, 25, 90, 40)
print(bucket_sort_custom(data, 5))

This approach teaches beginners how parameters can make functions reusable. It is a traditional programming idea that remains very important today.

Program 9: Bucket Sort handling negative and floating-point numbers

By default, Bucket Sort works best with positive numbers. This final program tweaks the logic to support negative values and decimals.

bucket_sort_extended <- function(arr) {

  min_val <- min(arr)
  max_val <- max(arr)
  bucket_count <- length(arr)

  buckets <- vector("list", bucket_count)

  for (num in arr) {

    index <- floor((num - min_val) / (max_val - min_val + 1) * bucket_count) + 1
    buckets[[index]] <- c(buckets[[index]], num)

  }

  result <- c()

  for (bucket in buckets) {

    if (length(bucket) > 0) {
      result <- c(result, sort(bucket))
    }

  }

  return(result)

}

data <- c(-12.5, 3.2, -7.1, 4.6, 0.5)
print(bucket_sort_extended(data))

This program shows how a classic algorithm can be adapted for real-world data. Beginners learn that most algorithms need small adjustments to handle practical scenarios like negative and floating-point numbers.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Bucket Sort in R in a simple and friendly way.

Q1. When should I use Bucket Sort in R?
Bucket Sort is best when the data is evenly distributed and the range of values is known. It is commonly used for percentages, scores, and normalized values.

Q2. Is Bucket Sort faster than Quick Sort?
Bucket Sort can be faster in specific situations, but Quick Sort is more general-purpose. The best choice depends on the type of data you are sorting.

Q3. Can Bucket Sort handle decimals?
Yes, with small tweaks like scaling or adjusting bucket ranges, Bucket Sort can handle floating-point numbers.

Q4. Is Bucket Sort stable?
Bucket Sort can be stable if the sorting method used inside each bucket is stable. This depends on the implementation.

Conclusion

Bucket Sort is a simple yet powerful sorting algorithm that helps beginners understand how dividing a problem into smaller parts can lead to clean and efficient solutions. By exploring multiple R programs, you can see how loops, helper functions, recursion, and small tweaks all play a role in solving the same problem.

With regular practice and experimentation, Bucket Sort becomes easy to understand and apply. Keep writing code, test different data, and explore how traditional algorithms still matter in modern programming. The more you practice, the more confident you will become with R and sorting techniques.

Scroll to Top