Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

Insertion Sort

Introduction

Insertion Sort is an easy-to-understand sorting algorithm that can be used to sort a list of elements. It works by dividing the input list into two parts: a sorted part and an unsorted part. At the beginning of the algorithm, the sorted part consists of just one element, and the unsorted part contains the rest of the elements. During each step of the algorithm, the first element from the unsorted part is inserted into the sorted part at the correct position. This process is repeated until the unsorted part becomes empty, and the sorted part contains all the elements in the desired order.

Insertion Sort is not the fastest sorting algorithm around, but it has some advantages that make it suitable for certain scenarios. For example, it is an in-place sorting algorithm, which means it doesn't use any additional memory to sort the list. Additionally, it is stable, which means that the relative order of equal elements is preserved.

Real-world Examples and Scenarios

Insertion Sort is an excellent choice for small datasets or when the data is partially sorted. It is also suitable for real-time systems where the data arrives continuously, and we need to maintain a sorted list at all times. Here are some real-world scenarios where Insertion Sort can be helpful:

  1. Sorting a small list of numbers.
  2. Organizing cards in a card game.
  3. Sorting a list of students by their grades.
  4. Maintaining a sorted list of stock prices or exchange rates for real-time trading applications.

Real-world Scenario and Technical Problem

Imagine you are a teacher who has just received the test scores of your students, and you need to sort them in ascending order to determine the class ranking. The number of students in the class is relatively small, so using Insertion Sort might be a suitable option to solve this problem.

Problem Statement

Given a list of student test scores, sort the list in non-decreasing order using the Insertion Sort algorithm.

Formal Definition

Input: A list scores of length n containing integers representing the test scores of students, where 1 <= n <= 100 and 0 <= scores[i] <= 100 for 0 <= i < n.

Output: A sorted list sorted_scores of length n containing the test scores in non-decreasing order.

Connecting the Problem Statement to the Real-world Scenario

The problem statement is directly related to the real-world scenario, as it requires sorting the list of student test scores in ascending order. Solving the problem using Insertion Sort will help the teacher to determine the class ranking efficiently.

Solution to the Problem

We will implement the Insertion Sort algorithm in Python to sort the list of student test scores. Here is a high-level overview of the algorithm:

  1. Iterate through the list starting from the second element (index 1).
  2. For each element, compare it with the elements to its left (sorted part).
  3. If the current element is smaller than the element to its left, swap the two elements.
  4. Repeat step 3 until the current element is at the correct position in the sorted part.
  5. Continue with the next element in the unsorted part.

Step-by-step Solution with the Real-world Scenario

Let's say we have the following test scores:

scores = [75, 85, 90, 50, 60, 95, 80, 70]

We will apply the Insertion Sort algorithm to sort these scores in ascending order.

  1. Start with the second element (85). It is already in the correct position relative to the first element (75), so no swaps are needed.
  2. Move to the third element (90). It is also in the correct position relative to the first two elements (75 and 85), so no swaps are needed.
  3. Move to the fourth element (50). It is smaller than the third element (90), so swap them.
  4. The fourth element (90) is now in the correct position relative to the first two elements (75 and 85). However, the first element (75) is greater than the second element (50), so swap them.
  5. The first element (75) is now in the correct position relative to the second element (50). The list is now [50, 75, 85, 90, 60, 95, 80, 70].
  6. Continue this process for the remaining elements in the list until the entire list is sorted.

Actual Code Solution with High-level Comments

def insertion_sort(scores):
    n = len(scores)

    # Iterate through the list starting from the second element
    for i in range(1, n):
        current_score = scores[i]
        j = i - 1

        # Find the correct position for the current_score in the sorted part
        while j >= 0 and scores[j] > current_score:
            scores[j + 1] = scores[j]
            j -= 1

        # Insert the current_score at the correct position
        scores[j + 1] = current_score

    return scores

# Test the insertion_sort function with our example test scores
scores = [75, 85, 90, 50, 60, 95, 80, 70]
sorted_scores = insertion_sort(scores)
print(sorted_scores)

Explanation of the Code Solution with Intuitions and Analogies

In the insertion_sort function, we first find the length of the input list scores. We then iterate through the list starting from the second element using a for loop. For each element, we compare it with the elements to its left (sorted part) by using a while loop.

Inside the while loop, we move the elements to the right until we find the correct position for the current element. Once we find the correct position, we insert the current element at that position. This process ensures that the sorted part of the list remains sorted after each iteration.

Finally, we return the sorted list of test scores.

How the Solution Can Solve Other Similar Real-world Problems

The Insertion Sort algorithm can be applied to various real-world problems that require sorting small datasets or maintaining a sorted list in real-time. Some examples include:

  1. Sorting a list of items by price in an online store.
  2. Organizing a list of tasks by priority in a task management application.
  3. Maintaining a sorted list of messages in a chat application.

By adjusting the comparison function in the Insertion Sort algorithm, you can sort lists based on different criteria (e.g., descending order, alphabetical order, etc.). This flexibility makes Insertion Sort a helpful tool for solving various sorting problems.