bubble sort in swift in swift

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. Here's how to implement the bubble sort algorithm in Swift:

main.swift
func bubbleSort<T: Comparable>(_ array: inout [T]) {
    guard array.count > 1 else {
        return
    }
    
    for i in 0..<array.count {
        var swapped = false
        for j in 1..<array.count-i {
            if array[j] < array[j-1] {
                array.swapAt(j, j-1)
                swapped = true
            }
        }
        if !swapped {
            return
        }
    }
}
398 chars
19 lines

To use the function, simply pass in an array of comparable elements:

main.swift
var numbers = [5, 2, 8, 10, 1]
bubbleSort(&numbers)
print(numbers) // [1, 2, 5, 8, 10]
87 chars
4 lines

Note that the inout keyword is used in the function signature to allow the function to modify the array in place.

related categories

gistlibby LogSnag