Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. """
  2. This code sort a list using quick sort with similar elements.
  3. """
  4. # L=input('Please insert list seperated with sapces: ')
  5. # L=L.split()
  6. # L=[int(L[i]) for i in range(len(L))]
  7. # p=0
  8. # r=len(L)-1]
  9. import random as rand # my python version is different
  10. def partition2(L,p,r):
  11.     x=L[r]
  12.     i1=p-1
  13.     i2=p-1
  14.     PP=False
  15.     for j in range(p,r):
  16.         if L[j]==x:
  17.             i2+=1
  18.             (L[j],L[i2])=(L[i2],L[j])
  19.             PP=True
  20.         elif L[j]<x:
  21.             if PP:
  22.                 i1+=1
  23.                 i2+=1
  24.                 (L[j],L[i1])=(L[i1],L[j])
  25.                 (L[i2],L[j])=(L[j],L[i2])
  26.             else:
  27.                 i1+=1
  28.                 i2+=1
  29.                 (L[j],L[i1])=(L[i1],L[j])
  30.     i2+=1
  31.     i1+=1
  32.     (L[r],L[i2])=(L[i2],L[r])
  33.     return (i1,i2)
  34. def randPartition2(L,p,r):
  35.     n=rand.randint(p,r) # my python version includes r while giving random numbers
  36.                           # so no need for +1
  37.     (L[n],L[r])=(L[r],L[n])
  38.     return partition2(L,p,r)
  39. # L=[5,6,5,5,1,3,5,2,1,7,9,5,15,100,5, 2,17,5,56]
  40. # print(randPartition2(L,0,len(L)-1))
  41. # print(L)
  42. def randQuickSort2(L):
  43.     def recrandQuickSort2(L,p,r):
  44.         if p<r:
  45.             (q1,q2)=randPartition2(L,p,r)
  46.             recrandQuickSort2(L,p,q1-1)
  47.             recrandQuickSort2(L,q2+1,r)
  48.     recrandQuickSort2(L,0,len(L)-1)
  49.     return L
  50. # # print(L)
  51. print(randQuickSort2([])) #A sorted: []
  52. print(randQuickSort2([1])) #A2=[1]
  53. print(randQuickSort2([0,1,2,0,1,2,0,1,2,1])) #[0, 0, 0, 1, 1, 1, 1, 2, 2, 2]
  54. print(randQuickSort2([5,6,5,5,1,3,5,2,1,7,9,5,15,100,5, 2,17,5,56]))
  55.                 #[1, 1, 2, 2, 3, 5, 5, 5, 5, 5, 5, 5, 6, 7,9, 15, 17, 56, 100]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement