Advertisement
Byleth_CYY

Nuts and Bolts

May 2nd, 2020
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. """
  2. class Comparator:
  3. def cmp(self, a, b)
  4. You can use Compare.cmp(a, b) to compare nuts "a" and bolts "b",
  5. if "a" is bigger than "b", it will return 1, else if they are equal,
  6. it will return 0, else if "a" is smaller than "b", it will return -1.
  7. When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid.
  8. """
  9.  
  10. from random import randint
  11. class Solution:
  12. # @param nuts: a list of integers
  13. # @param bolts: a list of integers
  14. # @param compare: a instance of Comparator
  15. # @return: nothing
  16. def sortNutsAndBolts(self, fnuts, fbolts, compare):
  17. # write your code here
  18. self.nuts=fnuts
  19. self.bolts=fbolts
  20. if not self.nuts or not self.bolts or len(self.nuts)!=len(self.bolts):
  21. return
  22. self.quicksort(0,len(self.nuts)-1,compare.cmp)
  23.  
  24. def quicksort(self,l,r,cmp):
  25. if l>=r:
  26. return
  27. pivot=self.bolts[randint(l,r)]
  28. i,j=l,r
  29. while i<=j:
  30. while i<=j and cmp(self.nuts[i],pivot)==-1:
  31. i+=1
  32. while i<=j and cmp(self.nuts[j],pivot)==1:
  33. j-=1
  34. if i<=j:
  35. self.nuts[i],self.nuts[j]=self.nuts[j],self.nuts[i]
  36. i+=1
  37. j-=1
  38. if i==j:
  39. self.quicksort_bolt(l,r,i,cmp)
  40. else:
  41. self.quicksort_bolt(l,r,i-1,cmp)
  42.  
  43. self.quicksort(l,j,cmp)
  44. self.quicksort(i,r,cmp)
  45. return
  46.  
  47. def quicksort_bolt(self,l,r,index,cmp):
  48. if l>=r:
  49. return
  50. pivot=self.nuts[index]
  51. i,j=l,r
  52. while i<=j:
  53. while i<=j and cmp(pivot,self.bolts[i])==1:
  54. i+=1
  55. while i<=j and cmp(pivot,self.bolts[j])==-1:
  56. j-=1
  57. if i<=j:
  58. self.bolts[i],self.bolts[j]=self.bolts[j],self.bolts[i]
  59. i+=1
  60. j-=1
  61. return
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement