R Program to Implement Selection Sort

1. Introduction

Selection Sort is another straightforward sorting algorithm. Its mechanism involves dividing the input list into two parts: a sorted and an unsorted sub-list. At every step, the algorithm seeks the smallest (or largest, depending on sorting order) element from the unsorted sub-list and swaps it with the leftmost unsorted element, thus extending the sorted sub-list by one element. In this guide, we will implement the Selection Sort algorithm in R.

2. Program Overview

The program will:

1. Define a function for the Selection Sort algorithm.

2. Create a vector with a series of numbers.

3. Use the Selection Sort function to sort the vector.

4. Display the sorted vector.

3. Code Program

# Define the Selection Sort function
selectionSort <- function(vec) {
  n <- length(vec)

  # Outer loop to move the boundary of the unsorted sub-list
  for (i in 1:(n-1)) {
    min_idx <- i
    # Inner loop to find the minimum element in the unsorted sub-list
    for (j in (i+1):n) {
      if (vec[j] < vec[min_idx]) {
        min_idx <- j
      }
    }
    # Swap the found minimum element with the first element of the unsorted sub-list
    temp <- vec[i]
    vec[i] <- vec[min_idx]
    vec[min_idx] <- temp
  }

  # Return the sorted vector
  return(vec)
}

# Create a vector
numbers <- c(56, 12, 89, 45, 23, 24)

# Sort the vector using Selection Sort
sorted_numbers <- selectionSort(numbers)

# Display the sorted vector
cat("Sorted vector using Selection Sort:", sorted_numbers, "\n")

Output:

Sorted vector using Selection Sort: 12 23 24 45 56 89

4. Step By Step Explanation

1. We initiate by defining the selectionSort function, which takes a vector as its argument and employs the Selection Sort algorithm to sort it.

2. The length function ascertains the length of the vector.

3. The outer loop sets the current boundary of the unsorted sub-list.

4. The inner loop scans the unsorted sub-list to detect the minimum element.

5. Once the minimum element is located, it is swapped with the first element of the unsorted sub-list.

6. After the entire sorting process, the function returns the sorted vector.

7. We then formulate a vector named "numbers" and apply the selectionSort function to sort it.

8. In the end, the sorted vector is printed using the cat function.

Note: The Selection Sort algorithm, while simple, is inefficient on larger lists and is generally outperformed by more advanced algorithms like quicksort or mergesort.

Comments