Skip to content

Instantly share code, notes, and snippets.

@rxtr007
Last active March 16, 2019 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rxtr007/e72657a387400b574115d6046f196ecc to your computer and use it in GitHub Desktop.
Save rxtr007/e72657a387400b574115d6046f196ecc to your computer and use it in GitHub Desktop.
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
}
}
@rxtr007
Copy link
Author

rxtr007 commented Mar 16, 2019

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]

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