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

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

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

算法原理

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

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;
};
相关推荐
go546315846524 分钟前
基于分组规则的Excel数据分组优化系统设计与实现
人工智能·学习·生成对抗网络·数学建模·语音识别
##echo25 分钟前
嵌入式Linux裸机开发笔记9(IMX6ULL)GPIO 中断实验(1)
linux·c语言·笔记·单片机·嵌入式硬件
●VON41 分钟前
重生之我在暑假学习微服务第二天《MybatisPlus-下篇》
java·学习·微服务·架构·mybatis-plus
Yu_Lijing1 小时前
MySQL进阶学习与初阶复习第四天
数据库·学习·mysql
好学且牛逼的马2 小时前
学习随笔录
学习
我爱学嵌入式3 小时前
C语言第 9 天学习笔记:数组(二维数组与字符数组)
c语言·笔记·学习
im_AMBER7 小时前
学习日志19 python
python·学习
爱装代码的小瓶子10 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
_Kayo_11 小时前
VUE2 学习笔记6 vue数据监测原理
vue.js·笔记·学习
chenchihwen11 小时前
大模型应用班-第2课 DeepSeek使用与提示词工程课程重点 学习ollama 安装 用deepseek-r1:1.5b 分析PDF 内容
人工智能·学习