Bubble sort.

Approach: Swap Adjacent elements from an array a[j] > a[j+1] then swap

// TC: O(n^2)
// SC: O(1)
func bubbleSort(_ arr: inout [Int]) {
    for i in 0..<arr.count-1 {
        for j in 0..<arr.count-i-1 {
            if arr[j] > arr[j+1] {
                arr.swapAt(j, j+1)
            }
        }
    }
}
var arrayToSort: [Int] = [9,2,11,4]
bubbleSort(&arrayToSort)
print("Sorted Array--> ", arrayToSort)// [2, 4, 9, 11]

Leave a Comment

Your email address will not be published. Required fields are marked *