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

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

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

算法原理

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

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;
};
相关推荐
浮灯Foden1 天前
算法-每日一题(DAY18)多数元素
开发语言·数据结构·c++·算法·leetcode·面试
violet-lz1 天前
数据结构八大排序:归并排序-原理+C语言实现+优化+面试题
c语言·数据结构·排序算法
如竟没有火炬1 天前
全排列——交换的思想
开发语言·数据结构·python·算法·leetcode·深度优先
浓墨染彩霞1 天前
Java----set
java·经验分享·笔记
浮游本尊1 天前
React 18.x 学习计划 - 第五天:React状态管理
前端·学习·react.js
baole9631 天前
YOLOv4简单基础学习
学习·yolo·目标跟踪
Pluchon1 天前
硅基计划5.0 MySQL 叁 E-R关系图&联合/多表查询&三大连接&子查询&合并查询
开发语言·数据库·学习·mysql
爱滑雪的码农1 天前
微信小程序页面配置,基本语法,页面切换,tabbar全局配置
笔记
学工科的皮皮志^_^1 天前
网口学习理解
经验分享·笔记·嵌入式硬件·学习·fpga开发·以太网
熬了夜的程序员1 天前
【LeetCode】82. 删除排序链表中的重复元素 II
数据结构·算法·leetcode·链表·职场和发展·矩阵·深度优先