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

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

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

算法原理

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

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;
};
相关推荐
小王C语言3 分钟前
【基础IO】————简单设计一下libc库
前端·数据结构·算法
_日拱一卒29 分钟前
LeetCode:滑动窗口的最大值
数据结构·算法·leetcode
老约家的可汗40 分钟前
list 容器详解:基本介绍与常见使用
c语言·数据结构·c++·list
Book思议-41 分钟前
【数据结构】字符串模式匹配:暴力算法与 KMP 算法实现与解析
数据结构·算法·kmp算法·bf算法
丝斯20111 小时前
AI学习笔记整理(79)——Python学习8
人工智能·笔记·学习
mifengxing1 小时前
力扣HOT100——(1)两数之和
java·数据结构·算法·leetcode·hot100
Z.风止1 小时前
Large Model-learning(2)
开发语言·笔记·python·leetcode
罗湖老棍子2 小时前
【 例 1】区间和(信息学奥赛一本通- P1547)(基础线段树和单点修改区间查询树状数组模版)
数据结构·算法·线段树·树状数组·单点修改 区间查询
啥咕啦呛2 小时前
java打卡学习5:java基础学习
java·开发语言·学习
Book思议-2 小时前
【数据结构】栈与队列核心对比
数据结构·栈与队列对比