当前位置: 首页 > news >正文

链表数组插入排序

InsertSort 

插入排序算法,比如打扑克牌的算法时,按照从左到右,找到对应的位置插入排序

最重要的是位置移动

找到对应位置值


#include "iostream"
#include "bits/stdc++.h"using namespace std;void sort(vector<int>& nums) {if(nums.size()==0) return;for(int i=1;i<nums.size();i++) {if(nums[i]<nums[i-1]) {int temp = nums[i];int j = i;while(j>0&&nums[j-1]>temp) {nums[j] = nums[j-1];j--;}nums[j] = temp;}}
}int main(int argc,char** argv) {vector<int> nums {2,3,2,12,19,23};sort(nums);for(int i:nums) {cout<<i<<" "<<endl;}return 0;
}

链表的插入排序算法:

没有灵魂的画手,SIX,SIX,SIX!


#include <string.h>
#include <iostream>
#include <bits/stdc++.h>using namespace std;struct ListNode {int val;struct ListNode *next;ListNode(int v):val(v) {}
};class Solution {
public:ListNode* insertionSortList(ListNode* head) {// 虚拟的头节点值。ListNode* dumb = new ListNode(-1);dumb->next = head;// head是最后一个已经排好序的位置// head->next是第一个待排序的位置while (head && head->next) {if (head->val > head->next->val) {// 从第一个节点的位置来进行遍历ListNode* p = dumb;while (p->next->val < head->next->val)  {p = p -> next;}ListNode* cur = head->next;head->next = cur->next;cur->next = p->next;p->next = cur;}else {head = head->next;}}// 删除虚拟的头指针节点值。head = dumb->next;delete dumb;return head;}
};int main(int argc, char* argv[]) {ListNode *head = new ListNode(1);ListNode *h2 = new ListNode(4);ListNode *h3 = new ListNode(3);ListNode *h4 = new ListNode(2);ListNode *h5 = new ListNode(5);ListNode *h6 = new ListNode(2);head->next = h2;h2->next = h3;h3->next = h4;h4->next = h5;h5->next = h6;h6->next = nullptr;Solution s;ListNode *res;res = s.insertionSortList(head);while(res!=nullptr) {cout<<res->val<<" ";res= res->next;}return 0;
}

http://www.lryc.cn/news/250878.html

相关文章:

  • MyBatis的创建,简单易懂的一篇blog
  • MOS管的静电击穿问题
  • 在线 SQL 模拟器SQL Fiddle使用简介
  • 仿京东淘宝商品列表筛选组件:实现一个高效的侧边栏弹框筛选功能
  • 软件工程 - 第8章 面向对象建模 - 4 - 物理体系结构建模
  • 【智能家居】二、添加火灾检测模块(烟雾报警功能点)
  • history和hash两种路由模式原理,和优缺点
  • Nginx 具体应用
  • 计算机网络之网络传输,三次握手和四次挥手
  • Azure Machine Learning - 在 Azure AI 搜索中创建全文查询
  • 基于YOLOv8深度学习的钢材表面缺陷检测系统【python源码+Pyqt5界面+数据集+训练代码】目标检测、深度学习实战
  • 深度学习常见回归分支算法逐步分析,各种回归之间的优缺点,适用场景,举例演示
  • Programming Contest 2023(AtCoder Beginner Contest 331)D题 Tile Pattern --- 题解
  • Google测试框架googletest简介与使用方法
  • 进程的创建:fork()
  • Fabric:创建应用通道
  • 力扣每日一题(2023-11-30)
  • 内部类Lambda
  • 设一棵二叉树中各结点的值互不相同,其先序遍历序列和中序遍历序列分别存于两个一维数组A[1...n]和 Bfl...n]中,试编写算法建立该二叉树的二叉链表。
  • 什么是Daily Scrum?
  • 逆波兰表达式求值[中等]
  • Oracle连接和使用
  • redis单线程为什么这么快
  • 工业机器视觉megauging(向光有光)使用说明书(五,轻量级的visionpro)
  • 【LittleXi】2023年广东工业大学腾讯杯新生程序设计竞赛
  • 【C语言:数据在内存中的存储】
  • 每日一练:阿姆斯特朗数
  • fatal: remote error: upload-pack: not our ref (未解决问题)
  • Python 3 使用 read()、readline()、readlines() 函数 读取文件
  • 勒索解密后oracle无法启动故障处理----惜分飞