单链表的选择排序

#include "List.h"
using namespace std;

Node* getSmall(Node* head)
{
    Node* smallPre = nullptr;
    Node* small    = head;
    Node* pre = head;
    Node* cur = head->next;
    while(cur)
    {
        if(cur->value < small->value)
        {
            smallPre = pre;
            small = cur;
        }
        pre = cur;
        cur = cur->next;
    }
    return smallPre;
}
Node* selectSort(Node* head)
{
    Node* tail = nullptr;
    Node* cur = head;
    Node* smallPre = nullptr;
    Node* small = nullptr;
    while(cur)
    {
        small = cur;
        smallPre = getSmall(cur);
        if(smallPre)
        {
            small = smallPre->next;
            smallPre->next = small->next;
        }
        cur = cur == small ? cur->next : cur;
        if(tail == nullptr)
            head = small;
        else
            tail->next = small;
        tail = small;
    }
    return head;
}

int main()
{
    Node* pNode0 = new Node(0);
    Node* pNode1 = new Node(1, pNode0);
    Node* pNode2 = new Node(2, pNode1);
    Node* pNode3 = new Node(2, pNode2);
    Node* pNode4 = new Node(1, pNode3);
    Node* pNode5 = new Node(0, pNode4);

    pNode5 = selectSort(pNode5);
    Print(pNode5);
}

猜你喜欢

转载自blog.csdn.net/wzc2608/article/details/80684260