Created
April 3, 2021 19:43
-
-
Save Roshankumar350/859191070e4e6d75bd03598b23d5b0cc to your computer and use it in GitHub Desktop.
Insertion Sort with Swift
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
func insertionSort(forInput input: inout [Int]) { | |
let uptoIndex = input.count - 1 | |
for rearIndex in 1...uptoIndex { | |
let rearValue = input[rearIndex] | |
var currentRunningIndex = rearIndex | |
while currentRunningIndex > 0 && input[currentRunningIndex - 1] > rearValue { | |
input[currentRunningIndex] = input[currentRunningIndex - 1] | |
currentRunningIndex -= 1 | |
} | |
input[currentRunningIndex] = rearValue | |
} | |
} | |
var unorderedArray = [1,5,3,9,7] | |
insertionSort(forInput: &unorderedArray) | |
print(unorderedArray) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment