【数据结构学习笔记】选择排序

【数据结构学习笔记】选择排序

参考电子书:排序算法精讲

算法原理

插入排序的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入

js 复制代码
const nums = [6, 3, 9, 1, 4];

// 从第一个开始,因为 nums[0] 天然有序
for (let i = 1; i < nums.length; i++) {
    // 取出当前值
    const current = nums[i];
    let j = i - 1;
    // 找到符合调节的 j
    while(j >= 0 && nums[j] > current) {
        // 数据后移
        nums[j + 1] = nums[j];
        // 指针向前移
        j--;
    }
    // 插入当前值
    nums[j + 1] = current;
}

相关例题

LC 147.对链表进行插入排序

给定单个链表的头 head ,使用 插入排序 对链表进行排序,并返回 排序后链表的头

js 复制代码
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var insertionSortList = function(head) {

    // 展开链表
    const nums = [];
    let current = head;
    while(current) {
        nums.push(current.val);
        current = current.next;
    }

    // 从第一个开始,因为 nums[0] 天然有序
    for (let i = 1; i < nums.length; i++) {
        // 取出当前值
        const current = nums[i];
        let j = i - 1;
        // 找到符合调节的 j
        while(j >= 0 && nums[j] > current) {
            // 数据后移
            nums[j + 1] = nums[j];
            // 指针向前移
            j--;
        }
        // 插入当前值
        nums[j + 1] = current;
    }

    // 拼接链表
    const newHead = new ListNode();
    let newCurrent = newHead;
    for (const num of nums) {
        const node = new ListNode(num);
        newCurrent.next = node;
        newCurrent = newCurrent.next
    }

    return newHead.next;
};
相关推荐
tiankongdeyige10 小时前
游戏战斗系统学习第2篇:有限状态机 (FSM)
学习·游戏·typescript
今晚打老虎12 小时前
c++之提高A(前缀和)(第三课)
数据结构·c++·算法
an123212113 小时前
ARM嵌入式学习笔记:SPI通信协议详解
arm开发·笔记·学习
不会就选b13 小时前
算法日常・每日刷题--<贪心>26
数据结构·算法
by2099914 小时前
从结构体到对象:正式学习C++类的骨架、封装与this指针
c++·经验分享·学习
乌暮14 小时前
深入理解 Java 泛型:把「万能盒子」用对、用稳
java·开发语言·后端·学习
小雪崩15 小时前
嵌入式学习 day60:ARM汇编——触摸屏与SPI
汇编·arm开发·学习
问天_观心16 小时前
大模型训练与推理优化(二)
人工智能·深度学习·学习·大模型·transformer
Because_of_Her116 小时前
dfs-洪水填充技巧
笔记·算法·深度优先·洪水填充
xzal1216 小时前
GESP Python笔记
笔记·python·算法