插入排序(InsertionSort),一般也被称为直接插入排序。改变了原有数组数据
    对于少量元素的排序,它是一个有效的算法。插入排序是一种最简单的排序方法,它的基本思想是将一个记录插入到已经排好序的有序表中,从而一个新的、记录数增 1 的有序表。
    在其实现过程使用双层循环,外层循环对除了第一个元素之外的所有元素,内层循环对当前元素前面有序表进行待插入位置查找,并进行移动。

    1.网上常规示例:

    1. ///插入排序
    2. func sortByInsertion2<T: Comparable>(_ a: [T]) -> [T] {
    3. let maxLenth = a.count
    4. var temp:[T] = a
    5. for i in 1..<maxLenth {
    6. //待插入元素---当前索引元素
    7. let current = temp[i]
    8. //当前元素前一个元素 不能为负值
    9. var preIndex = i - 1;
    10. while(preIndex >= 0 && temp[preIndex] > current){
    11. ///此时数组前index都是已经排好序的
    12. ///当前面preIndex值比当前current对应的值还小的时候 跳出循环
    13. ///此时数组里面有重复元素 在preIndex和preIndex+1
    14. ///只是在while语句跳出时候,将current的值赋值给preIndex+1罢了
    15. temp[preIndex+1] = temp[preIndex]
    16. preIndex -= 1
    17. }
    18. //将current给preIndex+1
    19. temp[preIndex+1] = current
    20. }
    21. return temp
    22. }

    2.个人理解示例:

    1. ///插入排序
    2. func sortByInsertion1<T: Comparable>(_ a: [T]) -> [T] {
    3. let maxLenth = a.count
    4. var temp:[T] = a
    5. for i in 1..<maxLenth {
    6. //待插入元素---当前索引元素
    7. let current = temp[i]
    8. var mixIndex = -1
    9. ///前面都是已经排序好的数据
    10. for j in 0..<i {
    11. if(temp[j] >= current){
    12. ///1.将当前元素插入到mixIndex位置
    13. ///2.数组增加了元素 所以要删除当前current元素 保持数组元素不变
    14. temp.insert(current, at: j)
    15. temp.remove(at: i+1)
    16. break
    17. }
    18. }
    19. }
    20. return temp
    21. }