Swift Program to Implement Shell Sort

Swift Program to Implement Shell Sort

Sorting is one of the most fundamental tasks in programming, and learning how different sorting algorithms work helps beginners understand the logic behind organizing data efficiently. One interesting algorithm is Shell Sort, which is an optimization of the classic insertion sort. It improves performance by comparing elements that are far apart and gradually reducing the gap between them until the array is fully sorted.

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

Shell Sort is widely used because it is simple to implement and performs better than basic sorting algorithms like bubble sort or insertion sort for medium-sized datasets. You will often see it in scenarios where memory is limited and a faster, in-place sort is needed. This article will guide you through multiple ways to implement Shell Sort in Swift, from simple loops to more advanced approaches, so you can understand and apply it in your own projects.

Program 1: Basic Shell Sort Using Loops

This program implements Shell Sort using straightforward loops. It starts with a large gap between elements and gradually reduces the gap until the array is sorted.

import Foundation

func shellSortLoop(_ array: inout [Int]) {

    let n = array.count
    var gap = n / 2

    while gap > 0 {

        for i in gap..<n {

            let temp = array[i]
            var j = i

            while j >= gap && array[j - gap] > temp {
                array[j] = array[j - gap]
                j -= gap
            }

            array[j] = temp

        }

        gap /= 2

    }

}

var data1 = [45, 23, 53, 12, 19, 8]

shellSortLoop(&data1)

print("Sorted array (loop):", data1)

This program works by initially comparing elements far apart to move larger numbers toward the end quickly. As the gap decreases, the array becomes almost sorted, making the final pass faster. Beginners can understand it as repeated insertion sorts with decreasing gaps.

Program 2: Shell Sort Using a Different Gap Sequence

Here, we demonstrate Shell Sort using the Knuth sequence for gaps, which sometimes improves sorting performance compared to halving the gap each time.

import Foundation

func shellSortKnuth(_ array: inout [Int]) {

    let n = array.count
    var gap = 1

    while gap < n / 3 {
        gap = 3 * gap + 1
    }

    while gap > 0 {

        for i in gap..<n {

            let temp = array[i]
            var j = i

            while j >= gap && array[j - gap] > temp {
                array[j] = array[j - gap]
                j -= gap
            }

            array[j] = temp

        }

        gap /= 3

    }

}

var data2 = [34, 8, 64, 51, 32, 21]

shellSortKnuth(&data2)

print("Sorted array (Knuth gap):", data2)

Using a custom gap sequence can sometimes reduce the number of comparisons, making the sort slightly faster. This helps beginners see how small tweaks in algorithms can affect efficiency.

Program 3: Shell Sort with Floating-Point Numbers

Shell Sort is not limited to integers. This example demonstrates sorting an array of doubles, showing its flexibility with comparable types.

import Foundation

func shellSortDouble(_ array: inout [Double]) {

    let n = array.count
    var gap = n / 2

    while gap > 0 {

        for i in gap..<n {

            let temp = array[i]
            var j = i

            while j >= gap && array[j - gap] > temp {
                array[j] = array[j - gap]
                j -= gap
            }

            array[j] = temp

        }

        gap /= 2

    }

}

var data3: [Double] = [0.5, 0.12, 0.99, 0.34, 0.21]

shellSortDouble(&data3)

print("Sorted array (double):", data3)

This demonstrates that Shell Sort works with any comparable type, making it practical for datasets beyond simple integers.

Program 4: Shell Sort Using a Function That Returns a Sorted Array

Sometimes, beginners prefer functions that return a new sorted array instead of sorting in place. This version demonstrates that approach.

import Foundation

func shellSortReturn(_ array: [Int]) -> [Int] {

    var sortedArray = array
    let n = sortedArray.count
    var gap = n / 2

    while gap > 0 {

        for i in gap..<n {

            let temp = sortedArray[i]
            var j = i

            while j >= gap && sortedArray[j - gap] > temp {
                sortedArray[j] = sortedArray[j - gap]
                j -= gap
            }

            sortedArray[j] = temp

        }

        gap /= 2

    }

    return sortedArray

}

let data4 = [25, 17, 31, 13, 2]
let sortedData4 = shellSortReturn(data4)

print("Sorted array (returning new array):", sortedData4)

This approach is helpful for functional programming patterns or when you want to avoid modifying the original array.

Program 5: Generic Shell Sort Using Comparable Types

This final example uses Swift generics to allow Shell Sort to work with any comparable type, including integers, doubles, or even custom objects.

import Foundation

func shellSortGeneric<T: Comparable>(_ array: [T]) -> [T] {

    var sortedArray = array
    let n = sortedArray.count
    var gap = n / 2

    while gap > 0 {

        for i in gap..<n {

            let temp = sortedArray[i]
            var j = i

            while j >= gap && sortedArray[j - gap] > temp {
                sortedArray[j] = sortedArray[j - gap]
                j -= gap
            }

            sortedArray[j] = temp

        }

        gap /= 2

    }

    return sortedArray

}

let data5 = [5.5, 2.2, 8.8, 1.1, 3.3]
let sortedData5 = shellSortGeneric(data5)

print("Sorted array (generic):", sortedData5)

Generics make this function reusable across different data types, teaching beginners the value of writing flexible and maintainable code.

Frequently Asked Questions (FAQ)

This section answers some of the most common questions beginners ask when learning Shell Sort in Swift.

Q1: Why use Shell Sort instead of Insertion Sort?
Shell Sort reduces the number of swaps and comparisons by moving elements far apart early on, which speeds up sorting for larger arrays compared to simple insertion sort.

Q2: Can Shell Sort handle floating-point numbers?
Yes, Shell Sort works with any type that conforms to the Comparable protocol, including integers, doubles, and even custom objects with a defined order.

Q3: Is Shell Sort stable?
Shell Sort is generally not stable, meaning equal elements may not retain their original order after sorting.

Q4: How do I choose the gap sequence?
The simplest approach is to halve the gap each time, but sequences like Knuth’s (3x + 1) may offer slightly better performance for larger arrays.

Q5: Should I sort arrays in place or return a new array?
Both approaches are valid. Sorting in place is more memory-efficient, while returning a new array can be safer if you need to preserve the original dataset.

Conclusion

Shell Sort is a practical and easy-to-understand sorting algorithm for beginners. By moving elements over larger gaps first, it reduces comparisons and performs better than simpler sorts like bubble sort. In Swift, you can implement it using loops, generics, or return-style functions, making it flexible for different data types and scenarios.

Practicing Shell Sort with integers, floating-point numbers, and even custom objects will help you understand the principles of efficient sorting and give you confidence to tackle more advanced algorithms in the future.

Scroll to Top