Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created July 26, 2018 21:30
Show Gist options
  • Save derekli66/74ee3b4e709cb8a7b0c537b293452b2f to your computer and use it in GitHub Desktop.
Save derekli66/74ee3b4e709cb8a7b0c537b293452b2f to your computer and use it in GitHub Desktop.
// Using Playground
func insertionSort(_ numbers: Array<Int>) -> Array<Int>
{
var nums = numbers
if (nums.count <= 1) { return nums }
for i in 1..<nums.count {
for j in (1...i).reversed() {
if (nums[j] < nums[j - 1]) {
// do swap
let temp = nums[j]
nums[j] = nums[j - 1]
nums[j - 1] = temp
}
else {
// suppose the array before index j is sorted
// no need for the next iteration
break
}
}
}
return nums
}
let array1 = [5, 4, 3, 2 ,1]
let array2 = [9, 5, 6, 11, 1, 2, 3, 4]
print(insertionSort(array1))
print(insertionSort(array2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment