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

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

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

算法原理

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

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;
};
相关推荐
虾球xz21 分钟前
游戏引擎学习第118天
学习·游戏引擎
gz927cool1 小时前
大模型做导师之开源项目学习(lightRAG)
学习·开源·mfc
电棍2331 小时前
verilog笔记
笔记·fpga开发
让我安静会1 小时前
Obsidian·Copilot 插件配置(让AI根据Obsidian笔记内容进行对话)
人工智能·笔记·copilot
世事如云有卷舒2 小时前
FreeRTOS学习笔记
笔记·学习
liuyuzhongcc3 小时前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
靡不有初1113 小时前
CCF-CSP第18次认证第一题——报数【两个与string相关的函数的使用】
c++·学习·ccfcsp
计算机小白一个4 小时前
蓝桥杯 Java B 组之背包问题、最长递增子序列(LIS)
java·数据结构·蓝桥杯
gu204 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
卑微的小鬼4 小时前
数据库使用B+树的原因
数据结构·b树