天天看點

連結清單-單連結清單的選擇排序

//單連結清單的選擇排序
public static Node selectSort(Node head){
    Node tail=null;//排序部分尾部
    Node cur=head;//未排序部分頭部
    Node smallPre=null;//最小節點的前一個節點
    Node small=null;//最小的節點
    while(cur!=null){
        small=cur;
        smallPre=getSmallestPreNode(cur);
        if(smallPre!=null){
            small=smallPre.next;
            smallPre.next=small.next;
        }
        cur=cur==small?cur.next:cur;
        if(tail==null){
            head=small;
        }else{
            tail.next=small;
        }
        tail=small;
    }
    return head;
}

public Node getSmallestPreNode(Node head){
    Node smallPre=null;
    Node small=head;
    Node cur=head.next;
    while(cur!=null){
        if(cur.value<small.value){
            smallPre=pre;
            small=cur;
        }
        pre=cur;
        cur=cur.next;
    }
    return smallPre;
}
           

繼續閱讀