sorting a doubly linked list with merge sort

前端 未结 5 1526
悲&欢浪女
悲&欢浪女 2020-12-02 01:33

I have found this code in the internet and it was for arrays ,I want to change it for doubly linked list(instead of index we should use pointer) would you please help me tha

5条回答
  •  执念已碎
    2020-12-02 02:36

    First of all, you must NOT use indexes when dealing with linked lists. Do it like this:

    while (i < in.size/2){
      listOne.addLast( in.remove(in.first()) );
      i++
    }
    while(!in.isEmptly){
      listTwo.addLast( in.remove(in.first()) );
    }
    

    And for merging

    merge(a, b, out){
      while(!a.empty && !b.empty){
        if(a.first() >= b.first())
          out.addLast( a.remove(a.first()) );
        else
         out.addLast( b.remove(b.first()) );
    
      //remember to take care of the remaining elements 
      while(!a.empty)
        out.addLast( a.remove(a.first()) );
      while(!b.empty)
        out.addLast( b.remove(b.first()) );
    }
    

    This way it will still be O(n log n)

提交回复
热议问题