R Program to Implement Insertion Sort

R Program to Implement Insertion Sort

Insertion Sort is one of the easiest and most natural sorting algorithms to understand. It works the same way people sort playing cards in their hands. You take one item at a time and place it in the correct position among the items you have already sorted. Because of this simple idea, Insertion Sort is often taught to beginners who are new to algorithms and programming.

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

Even though Insertion Sort is not the fastest sorting method for very large data, it is still very important. It performs well on small datasets and on data that is already partly sorted. In R programming, learning Insertion Sort helps you understand how loops, conditions, and vectors work together. These ideas are used everywhere in data analysis, whether you are working with numbers collected in Kenya or survey data from Zambia.

Program 1: Insertion Sort Using Basic For Loops

This program shows the most common and beginner-friendly way to implement Insertion Sort in R. It uses simple for loops and a predefined numeric vector.

# Insertion Sort using basic for loops

numbers <- c(8, 3, 5, 2, 9)

n <- length(numbers)

for (i in 2:n) {

  key <- numbers[i]
  j <- i - 1

  while (j > 0 && numbers[j] > key) {
    numbers[j + 1] <- numbers[j]
    j <- j - 1
  }

  numbers[j + 1] <- key

}

print(numbers)

This program works by taking one value at a time and inserting it into the correct position in the already sorted part of the vector. The while loop shifts larger values to the right to make space for the current value. Beginners like this approach because it clearly shows how sorting grows step by step from left to right.

Program 2: Insertion Sort Using a While Loop Only

This version uses while loops instead of for loops to control the sorting process. The logic stays the same, but the structure looks different.

# Insertion Sort using while loops

numbers <- c(12, 11, 13, 5, 6)

n <- length(numbers)
i <- 2

while (i <= n) {

  key <- numbers[i]
  j <- i - 1

  while (j > 0 && numbers[j] > key) {
    numbers[j + 1] <- numbers[j]
    j <- j - 1
  }

  numbers[j + 1] <- key
  i <- i + 1

}

print(numbers)

Here, the outer while loop moves through the vector, and the inner while loop finds the right place for the current value. This program is useful for beginners because it shows that the same algorithm can be written in different ways without changing the result.

Program 3: Insertion Sort Using a Custom Function

In this program, Insertion Sort is written as a function so it can be reused easily in other R scripts.

# Insertion Sort using a function

insertion_sort <- function(numbers) {

  n <- length(numbers)

  for (i in 2:n) {

    key <- numbers[i]
    j <- i - 1

    while (j > 0 && numbers[j] > key) {
      numbers[j + 1] <- numbers[j]
      j <- j - 1
    }

    numbers[j + 1] <- key

  }

  return(numbers)

}

data <- c(4, 10, 3, 5, 1)
sorted_data <- insertion_sort(data)

print(sorted_data)

This function takes a vector, sorts it using Insertion Sort, and returns the sorted result. Writing the algorithm as a function helps beginners understand how to organize code properly. It also makes the program easier to reuse when working on real data analysis tasks.

Program 4: Insertion Sort Using Recursion

This version uses recursion, where the function calls itself to solve smaller parts of the problem. It is more advanced but very helpful for learning.

# Recursive Insertion Sort

insertion_sort_recursive <- function(numbers, n) {

  if (n <= 1) {
    return(numbers)
  }

  numbers <- insertion_sort_recursive(numbers, n - 1)

  last <- numbers[n]
  j <- n - 1

  while (j > 0 && numbers[j] > last) {
    numbers[j + 1] <- numbers[j]
    j <- j - 1
  }

  numbers[j + 1] <- last
  return(numbers)

}

values <- c(9, 7, 5, 3, 1)
sorted_values <- insertion_sort_recursive(values, length(values))

print(sorted_values)

This program first sorts a smaller part of the vector and then inserts the last element into the correct position. It helps beginners understand recursion and how a big problem can be broken into smaller ones. While recursion is not always used in practice for sorting, it builds strong problem-solving skills.

Program 5: Insertion Sort with Negative and Floating Point Numbers

Insertion Sort in R works naturally with negative and decimal values, but this program shows that clearly using mixed data.

# Insertion Sort with negative and floating point numbers

numbers <- c(2.5, -1.2, 3.8, 0.0, -4.6)

n <- length(numbers)

for (i in 2:n) {

  key <- numbers[i]
  j <- i - 1

  while (j > 0 && numbers[j] > key) {
    numbers[j + 1] <- numbers[j]
    j <- j - 1
  }

  numbers[j + 1] <- key

}

print(numbers)

This program works exactly like the earlier ones, but it uses negative and floating point values. It shows beginners that Insertion Sort can handle real-world data such as temperatures, measurements, or prices collected in cities like Lusaka or Accra.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Insertion Sort in R in a simple and clear way.

Q1: Is Insertion Sort faster than Bubble Sort?
Insertion Sort is usually faster than Bubble Sort, especially when the data is already partly sorted. However, both are slow for very large datasets.

Q2: Why should I learn Insertion Sort when R has sort()?
Learning Insertion Sort helps you understand how sorting works internally. This knowledge is useful when learning more advanced algorithms later.

Q3: Can Insertion Sort work with strings in R?
Yes, Insertion Sort can sort strings as long as R can compare them. R sorts strings alphabetically by default.

Q4: Is recursion necessary for Insertion Sort?
Recursion is not necessary, but it is useful for learning. Loop-based versions are simpler and more common in real programs.

Q5: Where is Insertion Sort used in real life?
Insertion Sort is often used for small datasets or nearly sorted data. It is also widely used in teaching and learning.

Conclusion

Insertion Sort is a simple and powerful algorithm for beginners learning R programming. By working through loop-based programs, function-based solutions, and recursive versions, you can clearly see how values move into their correct positions. While it is not meant for huge datasets, it plays an important role in building strong programming foundations.

If you are new to R, practice these programs and try changing the input values. Like learning a traditional method passed down over time, mastering Insertion Sort will prepare you for more advanced sorting algorithms and data structures. Keep practicing, stay curious, and enjoy learning R one step at a time.

Scroll to Top