Skip to content

Commit a3ab980

Browse files
authored
random_normaldistribution_quicksort
This is for creating an algorithm implementing QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array and the array elements are taken from a Standard Normal Distribution. This is different from the ordinary quicksort in the sense, that it applies more to real life problems , where elements usually follow a normal distribution. Also the pivot is randomized to make it a more generic one.
1 parent d68666d commit a3ab980

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
from random import randint
2+
from tempfile import TemporaryFile
3+
import numpy as np
4+
import math
5+
6+
7+
8+
def _inPlaceQuickSort(A,start,end):
9+
count = 0
10+
if start<end:
11+
pivot=randint(start,end)
12+
temp=A[end]
13+
A[end]=A[pivot]
14+
A[pivot]=temp
15+
16+
p,count= _inPlacePartition(A,start,end)
17+
count += _inPlaceQuickSort(A,start,p-1)
18+
count += _inPlaceQuickSort(A,p+1,end)
19+
return count
20+
21+
def _inPlacePartition(A,start,end):
22+
23+
count = 0
24+
pivot= randint(start,end)
25+
temp=A[end]
26+
A[end]=A[pivot]
27+
A[pivot]=temp
28+
newPivotIndex=start-1
29+
for index in range(start,end):
30+
31+
count += 1
32+
if A[index]<A[end]:#check if current val is less than pivot value
33+
newPivotIndex=newPivotIndex+1
34+
temp=A[newPivotIndex]
35+
A[newPivotIndex]=A[index]
36+
A[index]=temp
37+
38+
temp=A[newPivotIndex+1]
39+
A[newPivotIndex+1]=A[end]
40+
A[end]=temp
41+
return newPivotIndex+1,count
42+
43+
outfile = TemporaryFile()
44+
p = 100 # 1000 elements are to be sorted
45+
46+
47+
48+
49+
mu, sigma = 0, 1 # mean and standard deviation
50+
X = np.random.normal(mu, sigma, p)
51+
np.save(outfile, X)
52+
print('The array is')
53+
print(X)
54+
55+
56+
57+
58+
59+
60+
outfile.seek(0) # using the same array
61+
M = np.load(outfile)
62+
r = (len(M)-1)
63+
z = _inPlaceQuickSort(M,0,r)
64+
65+
print("No of Comparisons for 100 elements selected from a standard normal distribution is :")
66+
print(z)

0 commit comments

Comments
 (0)