Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. import time
  2. import random
  3. def quicksort(arr, start=0, end=0):
  4. # a, b
  5. pivot = (end or len(arr)) - 1
  6. j = pivot - 1
  7. i = start
  8. # print("first step a: ", i, j, pivot,arr[0:pivot + 1])
  9. while(i<j):
  10. # c
  11. while(arr[i] < arr[pivot] and i < pivot):
  12. i+=1
  13. # print("stoped i at: ", i)
  14. while(arr[j] >arr[pivot] and j > 0):
  15. j-=1
  16. # print("stoped j at: ", j)
  17. if i < j and arr[i] > arr[j]:
  18. # print("swapped i and j : ", arr[i], arr[j])
  19. arr[i], arr[j] = arr[j], arr[i]
  20.  
  21. if arr[i] > arr[pivot]:
  22. # print("swapped i and pivot : ", arr[i], arr[pivot])
  23. arr[i], arr[pivot] = arr[pivot], arr[i]
  24. if (i>1):
  25. quicksort(arr,0,i)
  26.  
  27. if (pivot-i > 1):
  28. quicksort(arr, i+1, pivot+1)
  29.  
  30. def quicksort_with_recursion(arr):
  31. # a, b
  32. stack_box = [ [0,0] ]
  33. time_now = time.time()
  34. while(True):
  35. if len(stack_box) > 0:
  36. v = stack_box.pop()
  37. else:
  38. break
  39. pivot = (v[1] or len(arr)) - 1
  40. j = pivot - 1
  41. i = v[0]
  42. # print("first step a: ", i, j, pivot,arr[0:pivot + 1])
  43. while(i<j):
  44. # c
  45. while(arr[i] <= arr[pivot] and i < pivot):
  46. i+=1
  47. # print("stoped i at: ", i)
  48. while(arr[j] >= arr[pivot] and j > 0):
  49. j-=1
  50. # print("stoped j at: ", j)
  51. if i < j and arr[i] > arr[j]:
  52. # print("swapped i and j : ", arr[i], arr[j])
  53. arr[i], arr[j] = arr[j], arr[i]
  54. # import time
  55. # time.sleep(1)
  56. # print(i,"," ,j, " - ", arr[i],",", arr[j], "p", arr[pivot])
  57. if arr[i] > arr[pivot]:
  58. # print("swapped i and pivot : ", arr[i], arr[pivot])
  59. arr[i], arr[pivot] = arr[pivot], arr[i]
  60. # print("*", end="")
  61. if (i>1):
  62. stack_box.append([0,i])
  63.  
  64. if (pivot-i > 1):
  65. stack_box.append([i+1,pivot+1])
  66. # import time
  67. # time.sleep(1)
  68. x = time.time()
  69. if (x - time_now > 1):
  70. time_now = time.time()
  71. print( len(stack_box))
  72.  
  73.  
  74. def randomArrayGenerator(nos):
  75. values = []
  76. x = nos
  77. while(x > 0):
  78. y = random.randint(0, 1000)
  79. try:
  80. values.index(y)
  81. except:
  82. values.append(y)
  83. x -= 1
  84. return values
  85.  
  86.  
  87. def randomArrayGenerator2(nos):
  88. values = []
  89. for x in range(nos):
  90. y = len(values)
  91. pos = random.randint(0, y)
  92. values.insert(pos, x)
  93. return values
  94.  
  95.  
  96. sample2 = [4, 7, 12, 3, 27, 8]
  97.  
  98. nos = int(input("enter sample size: "))
  99. sample = randomArrayGenerator2(nos)
  100. print("sample is : ", sample)
  101. quicksort_with_recursion(sample)
  102. print("sorted sample is : ", sample)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement