Swift Program to Implement Quick Sort

Swift Program to Implement Quick Sort

Quick Sort is one of those classic sorting algorithms that every new programmer eventually comes across. It is fast, efficient, and widely used in many real-life systems. Even though the name sounds a little dramatic, the idea behind it is simple once you take a moment to understand how it works. Quick Sort uses a clever approach called divide and conquer, where a large problem is broken into smaller pieces until everything becomes easy to sort.

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

You will often see Quick Sort used when working with large datasets because it performs very well in most situations. Many libraries and built-in functions across different programming languages use some idea of Quick Sort underneath. Learning it not only helps you understand sorting better, but also helps you think in a more structured way about dividing problems into smaller parts. In Swift, Quick Sort becomes even more enjoyable to write because the language is clean, expressive, and very friendly for beginners.

Program 1: Basic Quick Sort Using Recursion

This first program shows a simple, classic Quick Sort function written in Swift using recursion. It uses a clear pivot-based approach, which helps beginners understand the core idea behind the algorithm. The data is predefined, so you can run the program as it is.

import Foundation

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

    if array.count <= 1 {
        return array
    }

    let pivot = array[array.count / 2]
    let smaller = array.filter { $0 < pivot }
    let equal = array.filter { $0 == pivot }
    let greater = array.filter { $0 > pivot }

    return quickSort(smaller) + equal + quickSort(greater)

}

let numbers = [29, 10, 14, 37, 13]
let result = quickSort(numbers)

print("Sorted array:", result)

This program picks the middle element as the pivot and splits the array into smaller, equal, and greater parts. The recursion continues until the array becomes small enough to return directly. Beginners find this method useful because it breaks Quick Sort into simple steps that match the idea of divide and conquer. The clean structure also helps you visualize how the data moves from unsorted to sorted.

Program 2: In-Place Quick Sort Using Partition Logic

This version uses an in-place algorithm, which means the array is sorted without creating new arrays. It uses the partition process to position the pivot and then applies recursion to the left and right sides of the array.

import Foundation

func partition(_ array: inout [Int], low: Int, high: Int) -> Int {

    let pivot = array[high]
    var i = low

    for j in low..<high {

        if array[j] < pivot {
            array.swapAt(i, j)
            i += 1
        }

    }

    array.swapAt(i, high)

    return i

}

func quickSortInPlace(_ array: inout [Int], low: Int, high: Int) {

    if low < high {

        let p = partition(&array, low: low, high: high)

        quickSortInPlace(&array, low: low, high: p - 1)
        quickSortInPlace(&array, low: p + 1, high: high)

    }

}

var data = [40, 20, 60, 10, 50, 30]

quickSortInPlace(&data, low: 0, high: data.count - 1)

print("In-place Quick Sort result:", data)

This approach helps you understand Quick Sort at a deeper level because it deals directly with the array’s memory. It is efficient and avoids creating extra arrays, which matters when sorting large data. Beginners who want to learn how the algorithm works behind the scenes will find this version very helpful.

Program 3: Quick Sort Using a Helper Function

This version uses a helper function that separates the partition logic and the main recursive sorting routine. It provides a clearer structure and can be easier to maintain and read.

import Foundation

func quickSortHelper(_ array: inout [Int], start: Int, end: Int) {

    if start >= end {
        return
    }

    let pivot = array[end]
    var boundary = start

    for i in start..<end {

        if array[i] < pivot {
            array.swapAt(i, boundary)
            boundary += 1
        }

    }

    array.swapAt(boundary, end)

    quickSortHelper(&array, start: start, end: boundary - 1)
    quickSortHelper(&array, start: boundary + 1, end: end)

}

var list = [7, 2, 9, 4, 3]

quickSortHelper(&list, start: 0, end: list.count - 1)

print("Sorted via helper-based Quick Sort:", list)

The helper function approach is helpful for beginners who want structure and separation of logic. By breaking the algorithm into sections, it becomes easier to debug and understand. It also shows how Quick Sort can be organized into cleaner parts, making the code more readable and reusable.

Program 4: Quick Sort Using Tuples and Returning Multiple Values

This example demonstrates a creative Swift-style Quick Sort using tuple return values to separate smaller and greater elements. It shows how Swift’s syntax can make algorithms cleaner.

import Foundation

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

    if array.count <= 1 {
        return array
    }

    let pivot = array[0]

    let split = array.dropFirst().reduce(into: ([Int](), [Int]())) { result, value in

        if value < pivot {
            result.0.append(value)
        } else {
            result.1.append(value)
        }

    }

    return quickSortWithTuples(split.0) + [pivot] + quickSortWithTuples(split.1)

}

let values = [31, 11, 22, 55, 44]
let sorted = quickSortWithTuples(values)

print("Tuple-based Quick Sort:", sorted)

This technique makes use of Swift’s ability to return multiple values cleanly. It helps beginners appreciate different ways to implement the same logic. It also shows how Swift’s built-in features can simplify algorithmic code and make it more expressive.

Program 5: Quick Sort Using Generics

In this version, Quick Sort is written as a generic function so it can sort any type that supports comparison, not just numbers. This adds flexibility and shows how Swift handles type constraints.

import Foundation

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

    if array.count <= 1 {
        return array
    }

    let pivot = array[array.count / 2]
    let smaller = array.filter { $0 < pivot }
    let equal = array.filter { $0 == pivot }
    let greater = array.filter { $0 > pivot }

    return genericQuickSort(smaller) + equal + genericQuickSort(greater)

}

// I. Sorting Strings
let words = ["apple", "zebra", "dog", "cat", "banana"]
let sortedWords = genericQuickSort(words)

print("Generic Quick Sort result (STRINGS):", sortedWords)

// II. Sorting Numbers
let numbers = [5, 1, 9, 2, 0, 6]
let sortedNumbers = genericQuickSort(numbers)

print("Generic Quick Sort result (NUMBERS):", sortedNumbers)

The power of this program lies in its flexibility. By using generics, you can sort strings, numbers, or any custom type. Beginners often find this useful because it shows how Swift lets you reuse logic without rewriting the same function several times. It is also a great introduction to generic programming.

Frequently Asked Questions (FAQ)

This section gives friendly answers to the questions many beginners ask when trying to understand how Quick Sort works in Swift. The goal is to make the ideas clear without using heavy technical language.

Q1: Why is Quick Sort so popular?
Quick Sort is popular because it is fast in most real situations and uses a smart divide-and-conquer strategy. It works well on large sets of data and often performs better than many other classic sorting methods. Many systems choose it because of this balance between speed and simplicity.

Q2: Can Quick Sort handle large lists efficiently?
Yes, Quick Sort handles large lists very well, especially when the data is spread out evenly. Its average performance is excellent, which is why many real applications rely on it. Even though it can slow down in rare worst cases, it remains one of the strongest choices for general sorting.

Q3: Is recursion required for Quick Sort?
Recursion is the most common way to write Quick Sort because it naturally fits the idea of splitting the array into smaller parts. However, recursion is not the only way. You can also write Quick Sort using loops and your own stack structure, though beginners usually find the recursive version easier to understand.

Q4: What is the difference between in-place and non-in-place Quick Sort?
An in-place Quick Sort rearranges the elements inside the same array, which means it uses very little extra memory. A non-in-place version creates new arrays during the sorting process, which is easier to read but uses more memory. Both work fine, but the in-place version is preferred when memory matters.

Q5: Can Quick Sort be used with custom objects in Swift?
Yes, Quick Sort works with custom objects as long as the type follows Swift’s Comparable rules. You simply make sure your object knows how to compare itself with another object of the same type. Once that is done, sorting custom data becomes as easy as sorting numbers or words.

Conclusion

Quick Sort is one of the most important sorting algorithms you will learn as a beginner, and understanding it opens the door to a deeper world of algorithmic thinking. Swift makes it enjoyable to experiment with different versions, from simple recursive approaches to advanced generic or in-place techniques. As you practice, you will see how each version has its own strengths and how the same idea can be expressed in many clean and powerful ways.

Keep exploring, try modifying the programs, and test them with different kinds of data. The more you play with Quick Sort, the easier algorithms will feel in your future programming journey.

Scroll to Top