-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimSorts.py
More file actions
424 lines (309 loc) · 9.9 KB
/
TimSorts.py
File metadata and controls
424 lines (309 loc) · 9.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#Merge Sort can be modified by the use of insertion sort
import numpy as np
# Python3 program to perform basic timSort
MIN_MERGE = 32
def calcMinRun(n):
"""Returns the minimum length of a
run from 23 - 64 so that
the len(array)/minrun is less than or
equal to a power of 2.
e.g. 1=>1, ..., 63=>63, 64=>32, 65=>33,
..., 127=>64, 128=>32, ...
"""
r = 0
while n >= MIN_MERGE:
r |= n & 1
n >>= 1
return n + r
# This function sorts array from left index to
# to right index which is of size atmost RUN
def insertionSort(arr, left, right):
for i in range(left + 1, right + 1):
j = i
while j > left and arr[j] < arr[j - 1]:
arr[j], arr[j - 1] = arr[j - 1], arr[j]
j -= 1
#TODO: Binary Insertion Sort
# Python Program implementation
# of binary insertion sort
def binary_search(arr, val, start, end):
# we need to distinguish whether we
# should insert before or after the
# left boundary. imagine [0] is the last
# step of the binary search and we need
# to decide where to insert -1
if start == end:
if arr[start] > val:
return start
else:
return start+1
# this occurs if we are moving
# beyond left's boundary meaning
# the left boundary is the least
# position to find a number greater than val
if start > end:
return start
mid = (start+end)//2
if arr[mid] < val:
return binary_search(arr, val, mid+1, end)
elif arr[mid] > val:
return binary_search(arr, val, start, mid-1)
else:
return mid
def insertion_sort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = binary_search(arr, val, 0, i-1)
arr = arr[:j] + [val] + arr[j:i] + arr[i+1:]
return arr
#___________________________________________________________
#Patience Sort
# Python code to implement the above approach
# Function to merge piles in a sorted order
def merge_piles(v):
# Store minimum element from the top of stack
ans = []
# In every iteration find the smallest element
# of top of pile and remove it from the piles
# and store into the final array
while True:
# Stores the smallest element of the top of the piles
minu = float("inf")
# Stores index of the smallest element of the top of the piles
index = -1
# Calculate the smallest element of the top of the every stack
for i in range(len(v)):
# If minu is greater than the top of the current stack
if minu > v[i][-1]:
# Update minu
minu = v[i][-1]
# Update index
index = i
# Insert the smallest element of the top of the stack
ans.append(minu)
# Remove the top element from the current pile
v[index].pop()
# If current pile is empty
if not v[index]:
# Remove current pile from all piles
v.pop(index)
# If all the piles are empty
if not v:
break
return ans
# Function to sort the given array using the patience sorting
def patienceSorting(arr):
# Store all the created piles
piles = []
# Traverse the array
for i in range(1, len(arr)):
# If no piles are created
if not piles:
# Initialize a new pile
temp = []
# Insert current element into the pile
temp.append(arr[i])
# Insert current pile into all the piles
piles.append(temp)
else:
# Check if top element of each pile is less than or equal to
# current element or not
flag = True
# Traverse all the piles
for j in range(len(piles)):
# Check if the element to be inserted is less than
# current pile's top
if arr[i] < piles[j][-1]:
piles[j].append(arr[i])
# Update flag
flag = False
break
# If flag is True
if flag:
# Create a new pile
temp = []
# Insert current element into temp
temp.append(arr[i])
# Insert current pile into all the piles
piles.append(temp)
# Store the sorted sequence of the given array
ans = []
# Sort the given array
ans = merge_piles(piles)
return ans
#-----------------------------------------------------
#-----------------------------
#shell sort
def shellSort(arr):
n = len(arr)
# code here
gap=n//2
while gap>0:
j=gap
# Check the array in from left to right
# Till the last possible index of j
while j<n:
i=j-gap # This will keep help in maintain gap value
while i>=0:
# If value on right side is already greater than left side value
# We don't do swap else we swap
if arr[i+gap]>arr[i]:
break
else:
arr[i+gap],arr[i]=arr[i],arr[i+gap]
i=i-gap # To check left side also
# If the element present is greater than current element
j+=1
gap=gap//2
return arr
#==================================
# Merge function merges the sorted runs
def merge(arr, l, m, r):
# original array is broken in two parts
# left and right array
len1, len2 = m - l + 1, r - m
left, right = [], []
for i in range(0, len1):
left.append(arr[l + i])
for i in range(0, len2):
right.append(arr[m + 1 + i])
i, j, k = 0, 0, l
# after comparing, we merge those two array
# in larger sub array
while i < len1 and j < len2:
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# Copy remaining elements of left, if any
while i < len1:
arr[k] = left[i]
k += 1
i += 1
# Copy remaining element of right, if any
while j < len2:
arr[k] = right[j]
k += 1
j += 1
# Iterative Timsort function to sort the
# array[0...n-1] (similar to merge sort)
def timSort(arr):
n = len(arr)
minRun = calcMinRun(n)
# Sort individual subarrays of size RUN
for start in range(0, n, minRun):
end = min(start + minRun - 1, n - 1)
insertionSort(arr, start, end)
# Start merging from size RUN (or 32). It will merge
# to form size 64, then 128, 256 and so on ....
size = minRun
while size < n:
# Pick starting point of left sub array. We
# are going to merge arr[left..left+size-1]
# and arr[left+size, left+2*size-1]
# After every merge, we increase left by 2*size
for left in range(0, n, 2 * size):
# Find ending point of left sub array
# mid+1 is starting point of right sub array
mid = min(n - 1, left + size - 1)
right = min((left + 2 * size - 1), (n - 1))
# Merge sub array arr[left.....mid] &
# arr[mid+1....right]
if mid < right:
merge(arr, left, mid, right)
size = 2 * size
# Iterative Timsort function to sort the
# array[0...n-1] (similar to merge sort)
def timSortBinary(arr):
n = len(arr)
minRun = calcMinRun(n)
# Sort individual subarrays of size RUN
for start in range(0, n, minRun):
end = min(start + minRun - 1, n - 1)
tempArr = insertion_sort(arr[start:end+1])
arr[start:end+1] = tempArr
# Start merging from size RUN (or 32). It will merge
# to form size 64, then 128, 256 and so on ....
size = minRun
while size < n:
# Pick starting point of left sub array. We
# are going to merge arr[left..left+size-1]
# and arr[left+size, left+2*size-1]
# After every merge, we increase left by 2*size
for left in range(0, n, 2 * size):
# Find ending point of left sub array
# mid+1 is starting point of right sub array
mid = min(n - 1, left + size - 1)
right = min((left + 2 * size - 1), (n - 1))
# Merge sub array arr[left.....mid] &
# arr[mid+1....right]
if mid < right:
merge(arr, left, mid, right)
size = 2 * size
# array[0...n-1] (similar to merge sort)
def timSortPatience(arr):
n = len(arr)
minRun = calcMinRun(n)
# Sort individual subarrays of size RUN
for start in range(0, n, minRun):
end = min(start + minRun - 1, n - 1)
tempArr = patienceSorting(arr[start:end+1])
arr[start:end] = tempArr
# Start merging from size RUN (or 32). It will merge
# to form size 64, then 128, 256 and so on ....
size = minRun
while size < n:
# Pick starting point of left sub array. We
# are going to merge arr[left..left+size-1]
# and arr[left+size, left+2*size-1]
# After every merge, we increase left by 2*size
for left in range(0, n, 2 * size):
# Find ending point of left sub array
# mid+1 is starting point of right sub array
mid = min(n - 1, left + size - 1)
right = min((left + 2 * size - 1), (n - 1))
# Merge sub array arr[left.....mid] &
# arr[mid+1....right]
if mid < right:
merge(arr, left, mid, right)
size = 2 * size
def timSortShell(arr):
n = len(arr)
minRun = calcMinRun(n)
# Sort individual subarrays of size RUN
for start in range(0, n, minRun):
end = min(start + minRun - 1, n - 1)
tempArr = shellSort(arr[start:end+1])
arr[start:end+1] = tempArr
# Start merging from size RUN (or 32). It will merge
# to form size 64, then 128, 256 and so on ....
size = minRun
while size < n:
# Pick starting point of left sub array. We
# are going to merge arr[left..left+size-1]
# and arr[left+size, left+2*size-1]
# After every merge, we increase left by 2*size
for left in range(0, n, 2 * size):
# Find ending point of left sub array
# mid+1 is starting point of right sub array
mid = min(n - 1, left + size - 1)
right = min((left + 2 * size - 1), (n - 1))
# Merge sub array arr[left.....mid] &
# arr[mid+1....right]
if mid < right:
merge(arr, left, mid, right)
size = 2 * size
# Driver program to test above function
# if __name__ == "__main__":
# arr = [-2, 7, 15, -14, 0, 15, 0,
# 7, -7, -4, -13, 5, 8, -14, 12]
# print("Given Array is")
# print(arr)
# big_array = list(np.random.randint(1, 1000, 500))
# print(big_array)
# # tempArr = insertion_sort(arr[3:7])
# timSortPatience(big_array)
# print(big_array)