Last active
March 16, 2019 04:19
-
-
Save rxtr007/e72657a387400b574115d6046f196ecc to your computer and use it in GitHub Desktop.
This file contains 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
extension Array where Element: Comparable { | |
func insertionSort() -> Array<Element> { | |
//check for trivial case | |
guard self.count > 1 else { | |
return self | |
} | |
//mutated copy | |
var output: Array<Element> = self | |
for primaryindex in 0..<output.count { | |
print("primaryindex: \(primaryindex)") | |
let key = output[primaryindex] | |
var secondaryindex = primaryindex | |
print("secondaryindex: \(secondaryindex),key : \(key)") | |
while secondaryindex > -1 { | |
if key < output[secondaryindex] { | |
//move to correct position | |
output.remove(at: secondaryindex + 1) | |
print(output) | |
output.insert(key, at: secondaryindex) | |
print(output) | |
} | |
secondaryindex -= 1 | |
print("secondaryindex : \(secondaryindex)") | |
} | |
} | |
return output | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample input - [1,2,8,4,3,-9]
primaryindex: 0
secondaryindex: 0,key : 1
secondaryindex : -1
primaryindex: 1
secondaryindex: 1,key : 2
secondaryindex : 0
secondaryindex : -1
primaryindex: 2
secondaryindex: 2,key : 8
secondaryindex : 1
secondaryindex : 0
secondaryindex : -1
primaryindex: 3
secondaryindex: 3,key : 4
secondaryindex : 2
[1, 2, 8, 3, -9]
[1, 2, 4, 8, 3, -9]
secondaryindex : 1
secondaryindex : 0
secondaryindex : -1
primaryindex: 4
secondaryindex: 4,key : 3
secondaryindex : 3
[1, 2, 4, 8, -9]
[1, 2, 4, 3, 8, -9]
secondaryindex : 2
[1, 2, 4, 8, -9]
[1, 2, 3, 4, 8, -9]
secondaryindex : 1
secondaryindex : 0
secondaryindex : -1
primaryindex: 5
secondaryindex: 5,key : -9
secondaryindex : 4
[1, 2, 3, 4, 8]
[1, 2, 3, 4, -9, 8]
secondaryindex : 3
[1, 2, 3, 4, 8]
[1, 2, 3, -9, 4, 8]
secondaryindex : 2
[1, 2, 3, 4, 8]
[1, 2, -9, 3, 4, 8]
secondaryindex : 1
[1, 2, 3, 4, 8]
[1, -9, 2, 3, 4, 8]
secondaryindex : 0
[1, 2, 3, 4, 8]
[-9, 1, 2, 3, 4, 8]
secondaryindex : -1
Final output - [-9, 1, 2, 3, 4, 8]