Skip to content

Instantly share code, notes, and snippets.

@cdunn95
Last active August 7, 2019 16:59
Show Gist options
  • Save cdunn95/77b1ea9dfd1a7a5409e3495d129af37e to your computer and use it in GitHub Desktop.
Save cdunn95/77b1ea9dfd1a7a5409e3495d129af37e to your computer and use it in GitHub Desktop.
Function to sort through an array of integers without using sort() or sorted()
import UIKit
func bubbleSort(_ array: inout [Int]){
for (i,_) in array.enumerated(){
if(i < array.count){
if(i<array.count - 1 && array[i] > array[i+1]){
let temp = array[i+1]
array[i+1] = array[i]
array[i] = temp
}
}
}
if(array[0]>array[1]){
let temp = array[0]
array[0] = array[1]
array[1] = temp
}
}
var array : [Int] = [3,6,2,4,5]
bubbleSort(&array)
@bhakes
Copy link

bhakes commented Aug 7, 2019

@cdunn2013 - Good work here. Looks like your algo is working properly.

There are a few optimizations that you could possibly make, most around helper functions that Swift gives us:

First, instead of using array.enumerated and ignoring the value at the index, we can just use array.indicies which returns a range from 0..<array.count.

Second, I don't think you need to use the if (i < array.count) check because the for (i,_) in array.enumerated() won't ever get to a point in which you'll be at i = array.count.

Lastly, array has an instance method called swapAt(_:_:) in which you can pass two indexes that you want to swap.

Here is what an optimization might look like:

func bubbleSort2(_ array: inout [Int]){
    
    var aSwapOccurred = true
    while aSwapOccurred {
        aSwapOccurred = false
        for i in array.indices {
            if (i < array.count - 1 && array[i] > array[i+1]) {
                array.swapAt(i, i+1)
                aSwapOccurred = true
            }
        }
    }
    
    
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment