链表数组插入排序

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;
}

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值