Swift Program to Implement Bubble Sort

Swift Program to Implement Bubble Sort

Bubble sort is one of the simplest sorting algorithms you will ever meet in your programming journey. Even though it is not the fastest or the most advanced method, it is perfect for beginners because it teaches how comparisons, swaps, and loops work together. When you learn bubble sort, you begin to understand how data can be arranged step-by-step until it becomes clean, ordered, and easy to work with.

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

This classic algorithm is used in learning environments, coding interviews, and small programs where performance is not a big concern. The main idea is straightforward: you repeatedly compare two nearby values and swap them when they are in the wrong order. After enough passes, the biggest numbers “bubble” to the end of the list, leaving the smaller ones neatly arranged in front. In the world of programming, this simple movement teaches an important foundation that helps you understand more complex sorting methods later on.

Program 1: Basic Bubble Sort Using a Simple Loop

This first program shows the most traditional way to implement bubble sort in Swift using two loops. It takes a predefined array of numbers and sorts them in ascending order. This simple example lets beginners see how passes and swaps happen clearly.

import Foundation

var numbers = [34, 12, 5, 66, 1, 89]

for i in 0..<numbers.count {

    for j in 0..<numbers.count - i - 1 {

        if numbers[j] > numbers[j + 1] {

            let temp = numbers[j]
            numbers[j] = numbers[j + 1]
            numbers[j + 1] = temp

        }

    }

}

print("Sorted Array:", numbers)

This version works by making several passes through the array. Each time the loops run, the biggest value moves to the end while the smaller numbers shift forward. Beginners often find this method helpful because it is easy to trace each step, and the logic is both familiar and predictable.

Program 2: Bubble Sort with a Swap Flag for Early Stopping

This program improves the basic bubble sort by adding a flag that checks if any swap was made during a pass. If the array is already sorted, the algorithm stops early, which makes it more efficient. It still uses predefined data, but now it avoids unnecessary work.

import Foundation

var numbers = [20, 14, 9, 2, 3]

for _ in 0..<numbers.count {

    var swapped = false

    for j in 0..<numbers.count - 1 {

        if numbers[j] > numbers[j + 1] {

            let temp = numbers[j]
            numbers[j] = numbers[j + 1]
            numbers[j + 1] = temp

            swapped = true

        }

    }

    if !swapped {
        break
    }

}

print("Sorted Array:", numbers)

This enhanced method works by checking if the data is already in order. When no swap happens during a pass, it knows the array is fully sorted and stops. This is useful in real code because it saves time and teaches, early on, the idea of optimizing simple algorithms.

Program 3: Bubble Sort Using a Function

Here, the sorting logic is placed inside a reusable Swift function. This helps beginners learn how to structure their code better and use functions to separate logic from the rest of a program. The function accepts an array and returns a sorted array.

import Foundation

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

    var nums = arr

    for i in 0..<nums.count {

        for j in 0..<nums.count - i - 1 {

            if nums[j] > nums[j + 1] {

                let temp = nums[j]
                nums[j] = nums[j + 1]
                nums[j + 1] = temp

            }

        }

    }

    return nums

}

let data = [45, 2, 90, 33, 12]
let sorted = bubbleSort(data)

print("Sorted Array:", sorted)

This program lets beginners understand how functions can wrap logic neatly while keeping the main part of the program clean and easy to read. It also shows how values can be passed and returned, which is a key part of Swift programming.

Program 4: Bubble Sort Using Recursion

This version takes a different approach by using recursion—where the function calls itself. The algorithm still follows the same bubble sort logic but performs it in repeated recursive calls instead of using a loop.

import Foundation

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

    if n == 1 {
        return
    }

    for j in 0..<n - 1 {

        if arr[j] > arr[j + 1] {

            let temp = arr[j]
            arr[j] = arr[j + 1]
            arr[j + 1] = temp

        }

    }

    recursiveBubble(&arr, n - 1)

}

var nums = [17, 3, 50, 27, 8]

recursiveBubble(&nums, nums.count)

print("Sorted Array:", nums)

The recursive approach helps beginners understand another fundamental concept in programming, where problems are solved by breaking them into smaller versions of themselves. While recursive bubble sort may not be used in real-world systems for performance reasons, it is an excellent learning tool.

Program 5: Bubble Sort in Descending Order

This final example shows how easy it is to adjust bubble sort to work in reverse. Instead of arranging numbers from smallest to biggest, this version sorts them from biggest to smallest. The logic only changes slightly, which helps beginners see how flexible bubble sort can be.

import Foundation

var items = [3, 11, 7, 29, 18]

for i in 0..<items.count {

    for j in 0..<items.count - i - 1 {

        if items[j] < items[j + 1] {

            let temp = items[j]
            items[j] = items[j + 1]
            items[j + 1] = temp

        }

    }

}

print("Sorted Descending:", items)

This method is helpful whenever you need the highest values first, such as ranking scores or arranging values for analysis. It also shows how small changes in comparison direction can create new behaviors in sorting methods.

Frequently Asked Questions (FAQ)

This section answers some common questions learners usually have when studying bubble sort in Swift.

Q1: Why is bubble sort taught so often to beginners?
Because it is simple, visual, and easy to follow. Even though it is not the fastest, it helps new learners understand sorting basics.

Q2: Is bubble sort used in real applications?
Most real systems use faster algorithms, but bubble sort is often used in classrooms, tutorials, and small training tasks.

Q3: How does bubble sort compare to selection sort or insertion sort?
Bubble sort tends to be slower, but it is easier to understand. Selection and insertion sort perform better in many cases.

Q4: Can bubble sort handle negative numbers?
Yes, it works with any numbers, including negatives, as long as you compare values correctly.

Q5: Is recursion better than loops for bubble sort?
Recursion is more of a teaching tool here. Loops are usually better for performance and readability.

Conclusion

Bubble sort may be one of the simplest sorting algorithms, but its value for beginners is huge. It teaches comparisons, swaps, loops, recursion, and problem-solving in a gentle way that feels natural and clear. With the programs above, you can explore Swift code from different angles and see how one idea can be expressed in several useful styles. Keep practicing, experiment with new arrays, and see how each version behaves. The more you try, the faster you will grow as a Swift programmer.

Scroll to Top