算法總結之 單鏈表的選擇排序


 給定一個無序單鏈表的頭節點head,實現單鏈表的選擇排序

要求額外空間復雜度O(1)

思路:

既然額外空間復雜度O(1),就不能把鏈表裝進容器,排好序后再從新鏈接,而是要求面試者在原鏈表上利用有限幾個變量完成選擇排序的過程。

  選擇排序是從未排序的部分找到最小值,然后放到排好序部分的尾部。

 

   1 開始時默認真個鏈表都是未排序的部分,對於找到的最小值節點肯定是整個鏈表的最小值節點,將其設置為新的頭節點記:newHead

   2 每次在排序的部分中找到最小值的節點,然后哦把這個節點從未排序的鏈表刪除,刪除的過程保證未排序的不能斷開

   3 把刪除的節點鏈接到排好序的后面

   4 全部過程處理完后,整個鏈表已經有序,返回newHead

 

package TT;

public class Test111 {

    public static class Node{
         public int value;
         public Node next;
         
         public Node(int data){
             this.value=data;
         }
    }
    
    
    public static Node selectionSort(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 static Node getSmallestPreNode(Node head){
        
          Node smallPre=null;
          Node small=head;
          Node pre = head;
          Node cur=head.next;
        
        while(cur!=null){
            if(cur.value <small.value){
                smallPre=pre;
                small=cur;
            }
            pre=cur;
            cur=cur.next;
        }
        return smallPre;
    }
    
    
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM