Iam_Sandeep

Quick sort on linked list

Apr 10th, 2022 (edited)
515
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. #with changing data fileds
  2. # Definition for singly-linked list.
  3. # class ListNode:
  4. #     def __init__(self, val=0, next=None):
  5. #         self.val = val
  6. #         self.next = next
  7. class Solution:
  8.     def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
  9.         def exchange(a,b):
  10.             a.val,b.val=b.val,a.val
  11.         def qsort(start,end):
  12.             if start!=end:
  13.                 piv=mid=start
  14.                 j=start.next
  15.                 while j:
  16.                     if j.val<piv.val:
  17.                         mid=mid.next
  18.                         exchange(j,mid)
  19.                     j=j.next
  20.                 exchange(mid,piv)
  21.                 qsort(start,mid)
  22.                 qsort(mid.next,end)
  23.         qsort(head,None)
  24.         return head
  25. #without changing data pointers ,data no swap code
  26. #User function Template for python3
  27.  
  28.  
  29. def quickSort(head):
  30.     def qsort(h):
  31.         if not h:return h#base case
  32.         dl,dm,dr=Node(-1),h,Node(-1)# temporary headers dm:equal dl:less than piv dr:gt than piv
  33.         l,m,r=dl,dm,dr#l,m,r traversing ptrs
  34.         piv,cur=h,h.next#pivot is head
  35.         while cur:#iterate cur
  36.             if cur.data==h.data:
  37.                 m.next=cur
  38.                 m=m.next
  39.             elif cur.data<h.data:
  40.                 l.next=cur
  41.                 l=l.next
  42.             else:
  43.                 r.next=cur
  44.                 r=r.next
  45.             cur=cur.next
  46.         l.next=r.next=m.next=None# ending the dl,dm,dr lists
  47.         dl.next=qsort(dl.next)
  48.         dr.next=qsort(dr.next)
  49.         res=dl#combining list
  50.         while res.next:
  51.             res=res.next
  52.         res.next=dm# since dm list have atleast one element for sure
  53.         m.next=dr.next
  54.         return dl.next
  55.     return qsort(head)
  56.            
  57.      
Add Comment
Please, Sign In to add comment