Swift Program to Implement Insertion Sort

Swift Program to Implement Insertion Sort

Insertion sort is one of the easiest sorting algorithms for beginners to understand because it works in a calm and natural way, almost like sorting cards in your hand. You take one value at a time and place it in the correct position among the values that came before it. This makes the algorithm feel familiar, predictable, and friendly for anyone just starting out in Swift programming. Its simple movement—pick, compare, shift, insert—helps you see how sorting happens step by step.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

While insertion sort is not the fastest method for very large data, it has great value in learning and small applications. It is often used in teaching, interviews, and real situations where the dataset is small and performance is not a big issue. The beauty of insertion sort is how clean and direct it is. Beginners can follow the flow easily, understand the logic clearly, and build confidence before moving on to more advanced sorting techniques in Swift.

Program 1: Basic Insertion Sort Using Simple Loops

This program presents the classic way to implement insertion sort in Swift using simple loops. It takes a predefined array, compares each value with the earlier ones, and places it in the right spot. This version helps beginners see the main idea of the algorithm in a clear and gentle way.

import Foundation

var numbers = [12, 11, 13, 5, 6]

for i in 1..<numbers.count {

    let key = numbers[i]
    var j = i - 1

    while j >= 0 && numbers[j] > key {
        numbers[j + 1] = numbers[j]
        j -= 1
    }

    numbers[j + 1] = key

}

print("Sorted Array:", numbers)

In this version, the value called key is pulled out and compared to earlier values. If a value is bigger than the key, it shifts one step to the right. When the right place is found, the key is placed there. Beginners understand this easily because the steps feel natural, almost like arranging items slowly and carefully.

Program 2: Insertion Sort Using a Swift Function

This program places the sorting logic inside a function, allowing cleaner organization and reusable code. It accepts an array, sorts it inside the function, and returns the finished result. This helps beginners learn how Swift functions can wrap logic neatly.

import Foundation

func insertionSort(_ arr: [Int]) -> [Int] {

    var nums = arr

    for i in 1..<nums.count {

        let key = nums[i]
        var j = i - 1

        while j >= 0 && nums[j] > key {
            nums[j + 1] = nums[j]
            j -= 1
        }

        nums[j + 1] = key

    }

    return nums

}

let data = [34, 8, 50, 21, 9]
let sorted = insertionSort(data)

print("Sorted Array:", sorted)

This approach is helpful because it keeps your main program short and clean. All the sorting happens inside the function, making the code easier to reuse in different projects. Beginners also learn the important idea of passing data into a function and receiving a processed version back.

Program 3: Insertion Sort in Descending Order

This program shows how easy it is to reverse the sorting order. Instead of arranging numbers from small to big, the algorithm places the largest values first. The change is small, yet it demonstrates how flexible insertion sort can be.

import Foundation

var items = [10, 3, 25, 7, 18]

for i in 1..<items.count {

    let key = items[i]
    var j = i - 1

    while j >= 0 && items[j] < key {
        items[j + 1] = items[j]
        j -= 1
    }

    items[j + 1] = key

}

print("Sorted Descending:", items)

This version works well when you want the highest values at the beginning, such as ranking results or organizing scores. It shows beginners how tiny changes in comparison direction create new outcomes. This builds confidence in understanding how sorting logic works.

Program 4: Recursive Insertion Sort

This program shows insertion sort using recursion instead of loops. The idea is the same, but the algorithm sorts the first part of the array and then inserts the next value in the correct spot through repeated function calls.

import Foundation

func recursiveInsertion(_ arr: inout [Int], _ n: Int) {

    if n <= 1 {
        return
    }

    recursiveInsertion(&arr, n - 1)

    let last = arr[n - 1]
    var j = n - 2

    while j >= 0 && arr[j] > last {
        arr[j + 1] = arr[j]
        j -= 1
    }

    arr[j + 1] = last

}

var numbers2 = [15, 4, 23, 8, 16]

recursiveInsertion(&numbers2, numbers2.count)

print("Sorted Array:", numbers2)

This method is useful for learning how recursion can break a problem into smaller parts. Even though recursion is usually not the fastest way to sort, it teaches beginners an important concept used in many other algorithms. It also shows that the same idea can be expressed in different forms.

Program 5: Insertion Sort with a Helper Function for Insertion

This version separates the insertion step into its own helper function. This breaks the algorithm into smaller pieces, making the code easier to read and understand. It teaches beginners how to organize logic into neat and reusable parts.

import Foundation

func insertElement(_ arr: inout [Int], _ index: Int) {

    let key = arr[index]
    var j = index - 1

    while j >= 0 && arr[j] > key {
        arr[j + 1] = arr[j]
        j -= 1
    }

    arr[j + 1] = key

}

var sample = [30, 12, 45, 20, 5]

for i in 1..<sample.count {
    insertElement(&sample, i)
}

print("Sorted Array:", sample)

This approach helps beginners see the algorithm in smaller, clear steps. One part focuses on scanning and calling the helper function, while the helper function handles the careful placement of the key value. It also builds good habits for writing clean and organized Swift code.

Frequently Asked Questions (FAQ)

This section answers popular questions from learners who want to understand insertion sort more deeply.

Q1: Why is insertion sort good for beginners?
It has simple steps that match how people naturally sort things, making it easy to understand and practice.

Q2: Is insertion sort fast for large data?
It works well for small datasets, but for very large lists, faster algorithms are usually better.

Q3: Can insertion sort handle negative numbers?
Yes, it sorts all kinds of integers as long as comparisons are done correctly.

Q4: Is the recursive version better than loops?
Recursion helps with learning concepts, but loops are generally simpler and faster for insertion sort.

Q5: Why does insertion sort perform well on nearly sorted data?
Because it only shifts a few values when the array is already close to being sorted, making it very efficient in such cases.

Conclusion

Insertion sort is a gentle and beginner-friendly sorting algorithm that teaches core ideas in a simple and clear way. It helps you understand comparisons, shifts, recursion, and how data finds its correct place. With the different Swift programs shown above, you can explore the algorithm from multiple angles and build strong confidence in your coding skills. Keep practicing, try changing the arrays, and see how the algorithm behaves. More experience will make sorting feel natural, and you will be ready for more advanced algorithms in no time.

Scroll to Top