Last active
August 7, 2019 16:59
-
-
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()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 usearray.indicies
which returns a range from0..<array.count
.Second, I don't think you need to use the
if (i < array.count)
check because thefor (i,_) in array.enumerated()
won't ever get to a point in which you'll be ati = array.count
.Lastly,
array
has an instance method calledswapAt(_:_:)
in which you can pass two indexes that you want to swap.Here is what an optimization might look like: