合肥集团网站建设公司,微信公众号内容编辑及排版,家用电脑和宽带做网站,阿坝住房和城乡建设厅网站InsertSort
插入排序算法#xff0c;比如打扑克牌的算法时#xff0c;按照从左到右#xff0c;找到对应的位置插入排序
最重要的是位置移动
找到对应位置值 #include iostream
#include bits/stdc.husing namespace std;void sort(vectorin…InsertSort
插入排序算法比如打扑克牌的算法时按照从左到右找到对应的位置插入排序
最重要的是位置移动
找到对应位置值 #include iostream
#include bits/stdc.husing namespace std;void sort(vectorint nums) {if(nums.size()0) return;for(int i1;inums.size();i) {if(nums[i]nums[i-1]) {int temp nums[i];int j i;while(j0nums[j-1]temp) {nums[j] nums[j-1];j--;}nums[j] temp;}}
}int main(int argc,char** argv) {vectorint nums {2,3,2,12,19,23};sort(nums);for(int i:nums) {couti endl;}return 0;
}链表的插入排序算法
没有灵魂的画手SIXSIXSIX #include string.h
#include iostream
#include bits/stdc.husing 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) {coutres-val ;res res-next;}return 0;
}