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

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

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

算法原理

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

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;
};
相关推荐
Brookty10 分钟前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
UQI-LIUWJ16 分钟前
计算机组成笔记:缓存替换算法
笔记·缓存
DKPT24 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
2401_8812444043 分钟前
Treap树
数据结构·算法
乌萨奇也要立志学C++44 分钟前
二叉树OJ题(单值树、相同树、找子树、构建和遍历)
数据结构·算法
编程小白gogogo1 小时前
Spring学习笔记
笔记·学习·spring
qq_527887871 小时前
【学习笔记】Python中主函数调用的方式
笔记·学习
二闹1 小时前
第十六章:监理基础知识(16.1监理的意义和作用--16.5监理要素)
笔记·产品经理
Chef_Chen1 小时前
从0开始学习R语言--Day37--CMH检验
学习
致***锌2 小时前
etf期权和个股期权哪个期权费更贵?
笔记