2025-xx-xx_sort-routines-in-python.html


001| #:name::Sort Routines in Python
002| #:link::
003| #:date::2025-xx-xx
004| #:code::
005| from random import random
006| 
007| Count  = 1000
008| ValMin =    0
009| ValMax =  100
010| 
011| RandNum = lambda mn,mx: (mn+(random()*(mx-mn)))
012| 
013| RandNums = [RandNum(ValMin,ValMax) for _ in range(Count)]
014| 
015| def list_is_sorted (xs):
016|     '''Determine if a list is sorted.'''
017|     x0 = min(xs)
018| 
019|     for x in xs:
020|         if x < x0:
021|             return False
022|         x0 = x
023| 
024|     return True
025| 
026| 
027| if __name__ == '__main__':
028|     print()
029|     print(f'count: {Count}')
030|     print(f'min-nbr: {min(RandNums)}')
031|     print(f'max-nbr: {max(RandNums)}')
032|     print(f'head: {RandNums[:3]} ...')
033|     print(f'tail: ... {RandNums[-3:]}')
034|     print()
035| 
036| #:code::
037| from random import random
038| 
039| Count  = 1000
040| ValMin =    0
041| ValMax =  100
042| 
043| RandNum = lambda mn,mx: (mn+(random()*(mx-mn)))
044| 
045| RandNums = [RandNum(ValMin,ValMax) for _ in range(Count)]
046| 
047| def list_is_sorted (xs):
048|     '''Determine if a list is sorted.'''
049|     x0 = min(xs)
050| 
051|     for x in xs:
052|         if x < x0:
053|             return False
054|         x0 = x
055| 
056|     return True
057| 
058| # Set value to:
059| # 0 to generate new RandNums;
060| # 1 to load savefile;
061| # 2 to create savefile
062| load_or_make_savefile = 0
063| 
064| SaveFile = r'C:\demo\hcc\python\randnums.dat'
065| 
066| if load_or_make_savefile == 1:
067|     # Load random numbers savefile...
068|     fdat = open(SaveFile, mode='r', encoding='utf8')
069|     try:
070|         RandNums = [float(n) for n in fdat]
071|     except:
072|         raise
073|     finally:
074|         fdat.close()
075|         print(f'read: {SaveFile} ({len(RandNums)} numbers)')
076| 
077| elif load_or_make_savefile == 2:
078|     # Write random numbers savefile...
079|     fdat = open(SaveFile, mode='w', encoding='utf8')
080|     try:
081|         for n in RandNums:
082|             print(str(n), file=fdat)
083|     except:
084|         raise
085|     finally:
086|         fdat.close()
087|         print(f'wrote: {SaveFile} ({len(RandNums)} numbers)')
088| 
089| 
090| if __name__ == '__main__':
091|     print()
092|     print(f'count: {Count}')
093|     print(f'min-nbr: {min(RandNums)}')
094|     print(f'max-nbr: {max(RandNums)}')
095|     print(f'head: {RandNums[:3]} ...')
096|     print(f'tail: ... {RandNums[-3:]}')
097|     print()
098| 
099| #:code::
100| from examples import RandNums, list_is_sorted
101| 
102| def bubble (xs):
103|     '''BUBBLE SORT. [https://en.wikipedia.org/wiki/Bubble_sort]'''
104|     print(f'Bubble Sort ({len(xs)} items)')
105|     stats = [0, 0] # passes, swaps
106| 
107|     def sort_pass ():
108|         # Assume list is sorted...
109|         flag = False
110| 
111|         # Iterate over list (skipping last element)...
112|         for ix in range(len(xs)-1):
113| 
114|             # If next element is less than current element...
115|             if xs[ix+1] < xs[ix]:
116|                 #print(f'swap: {ix} <-> {ix+1}')
117|                 stats[1] += 1
118| 
119|                 # Swap current and next elements...
120|                 tmp = xs[ix]
121|                 xs[ix] = xs[ix+1]
122|                 xs[ix+1] = tmp
123| 
124|                 # Flag that we did a swap...
125|                 flag = True
126| 
127|         # Return True if we made a swap, else False...
128|         return flag
129| 
130|     # Do sort passes until list is sorted...
131|     while sort_pass():
132|         stats[0] += 1
133| 
134|     print(f'passes: {stats[0]}; swaps: {stats[1]:,}')
135| 
136|     # Return list...
137|     return xs
138| 
139| if __name__ == '__main__':
140|     sortedNums = bubble(list(RandNums))
141| 
142|     print(f'list-is-sorted: {list_is_sorted(sortedNums)}')
143|     print()
144| 
145| #:code::
146| from examples import RandNums, list_is_sorted
147| 
148| def shaker (xs):
149|     '''SHAKER SORT. [just another type of bubble sort]'''
150|     print(f'Shaker Sort ({len(xs)} items)')
151|     stats = [0, 0, 0] # passes, swaps-up, swaps-down
152| 
153|     def sort_pass ():
154|         # Assume list is sorted...
155|         flag = False
156| 
157|         # Iterate forwards over list (skipping last element)...
158|         for ix in range(len(xs)-1):
159| 
160|             # If next element is less than current element...
161|             if xs[ix+1] < xs[ix]:
162|                 #print(f'swap: {ix} <-> {ix+1}')
163|                 stats[1] += 1
164| 
165|                 tmp = xs[ix]
166|                 xs[ix] = xs[ix+1]
167|                 xs[ix+1] = tmp
168|                 flag = True
169| 
170|         # Iterate backwards over list (skipping first element)...
171|         for ix in range(len(xs)-1, 1, -1):
172| 
173|             # If next element is less than current element...
174|             if xs[ix] < xs[ix-1]:
175|                 #print(f'swap: {ix} <-> {ix-1}')
176|                 stats[2] += 1
177| 
178|                 tmp = xs[ix]
179|                 xs[ix] = xs[ix-1]
180|                 xs[ix-1] = tmp
181|                 flag = True
182| 
183|         # Return True if we made a swap, else False...
184|         return flag
185| 
186|     # Do sort passes until list is sorted...
187|     while sort_pass():
188|         stats[0] += 1
189| 
190|     print(f'passes: {stats[0]}')
191|     print(f'swaps-up: {stats[1]:,}; swaps-down: {stats[2]:,}')
192| 
193|     # Return list...
194|     return xs
195| 
196| if __name__ == '__main__':
197|     sortedNums = shaker(list(RandNums))
198| 
199|     print(f'list-is-sorted: {list_is_sorted(sortedNums)}')
200|     print()
201| 
202| #:code::
203| from examples import RandNums, list_is_sorted
204| 
205| def insertion (xs):
206|     '''INSERTION SORT. [https://en.wikipedia.org/wiki/Insertion_sort]'''
207|     print(f'Insertion Sort ({len(xs)} items)')
208|     swaps = 0
209| 
210|     # Iterate over list (skipping element 0)...
211|     for ix in range(1, len(xs)):
212| 
213|         # Iterate from here back to list start...
214|         jx = ix
215| 
216|         # If lower element is greater than curr element...
217|         while (0 < jx) and (xs[jx] < xs[jx-1]):
218| 
219|             # Swap lower and current elements...
220|             #print(f'swap: {jx-1} <-> {jx}')
221|             swaps += 1
222| 
223|             tmp = xs[jx-1]
224|             xs[jx-1] = xs[jx]
225|             xs[jx] = tmp
226| 
227|             # Next lower element...
228|             jx -= 1
229| 
230|     print(f'total-swaps: {swaps:,}')
231| 
232|     # Return list...
233|     return xs
234| 
235| if __name__ == '__main__':
236|     sortedNums = insertion(list(RandNums))
237| 
238|     print(f'list-is-sorted: {list_is_sorted(sortedNums)}')
239|     print()
240| 
241| #:code::
242| from examples import RandNums, list_is_sorted
243| 
244| def selection (xs):
245|     '''SELECTION SORT. [https://en.wikipedia.org/wiki/Selection_sort]'''
246|     print(f'Selection Sort ({len(xs)} items)')
247|     swaps = 0
248| 
249|     # Iterate over list (skipping element 0)...
250|     for ix in range(len(xs)):
251| 
252|         # Assume current item is the minimum item...
253|         mx = ix
254| 
255|         # Test against remaining items to find smallest...
256|         for jx in range(ix+1, len(xs)):
257| 
258|             if xs[jx] < xs[mx]:
259|                 # Found a smaller item...
260|                 mx = jx
261| 
262|         # If our assumption was wrong...
263|         if mx != ix:
264|             # Swap minimum with current item...
265|             #print(f'swap: {ix} <-> {mx}')
266|             swaps += 1
267| 
268|             tmp = xs[ix]
269|             xs[ix] = xs[mx]
270|             xs[mx] = tmp
271| 
272|     print(f'total-swaps: {swaps:,}')
273| 
274|     # Return list...
275|     return xs
276| 
277| if __name__ == '__main__':
278|     sortedNums = selection(list(RandNums))
279| 
280|     print(f'list-is-sorted: {list_is_sorted(sortedNums)}')
281|     print()
282| 
283| #:code::
284| from examples import RandNums, list_is_sorted
285| 
286| def merge (xs):
287|     '''MERGE SORT.' [https://en.wikipedia.org/wiki/Merge_sort]'''
288|     print(f'Merge Sort ({len(xs)} items)')
289|     calls = [0, 0]
290| 
291|     def merge_combine(left, right):
292|         '''Combine two sorted lists.'''
293|         calls[1] += 1
294| 
295|         buff = []
296|         lx = 0
297|         rx = 0
298| 
299|         # While both lists have elements...
300|         while (lx < len(left)) and (rx < len(right)):
301| 
302|             # If left <= right...
303|             if left[lx] <= right[rx]:
304|                 # Buffer the left item...
305|                 buff.append(left[lx])
306|                 # And remove it...
307|                 lx += 1
308|             else:
309|                 # Else right < left, so buffer right item...
310|                 buff.append(right[rx])
311|                 # And remove it...
312|                 rx += 1
313| 
314|         # At least one lists is empty, so put any remainder in the buffer...
315|         # (Possibly both lists are empty at this point.)
316|         buff.extend(left[lx:])
317|         buff.extend(right[rx:])
318| 
319|         # Return the buffer contents...
320|         return buff
321| 
322|     def merge_sort (xs):
323|         '''Recursive merge sort function.'''
324|         calls[0] += 1
325| 
326|         # If list is empty or has one element, it's already sorted...
327|         if len(xs) <= 1:
328|             return xs
329| 
330|         # Pick the list's midpoint...
331|         mid = len(xs) // 2
332| 
333|         # Return the sorted combination of the two halves...
334|         # NOTE THE DOUBLE RECURSION!
335|         return merge_combine(merge_sort(xs[:mid]), merge_sort(xs[mid:]))
336| 
337|     xs = merge_sort(xs)
338| 
339|     print(f'merge_sort: {calls[0]} calls; merge_combine: {calls[1]} calls')
340| 
341|     # Return list...
342|     return xs
343| 
344| if __name__ == '__main__':
345|     sortedNums = merge(list(RandNums))
346| 
347|     print(f'list-is-sorted: {list_is_sorted(sortedNums)}')
348|     print()
349| 
350| #:code::
351| from math import floor
352| from examples import RandNums, list_is_sorted
353| 
354| def heapsort (xs):
355|     '''HEAP SORT [https://en.wikipedia.org/wiki/Heapsort].'''
356|     print(f'Heap Sort ({len(xs)} items)')
357|     stats = [0, 0, 0] # heapify passes; sift_down calls; sift_down swaps
358| 
359|     left_child = lambda n: (2*n)+1
360| 
361|     # Repair heap whose root element is at index 'start',
362|     # assuming the heaps rooted at its children are valid.
363|     def sift_down(xs, root, end):
364|         '''After sifting down the root, all elements are in heap order.'''
365|         stats[1] += 1
366| 
367|         # Loop while root has at least one child...
368|         while left_child(root) < end:
369| 
370|             # Left child of root...
371|             child = left_child(root)
372| 
373|             # If there is a right child and it is greater...
374|             if (child+1 < end) and (xs[child] < xs[child+1]):
375|                 child += 1
376| 
377|             if xs[root] < xs[child]:
378|                 # Swap root and child...
379|                 stats[2] += 1
380| 
381|                 tmp = xs[root]
382|                 xs[root] = xs[child]
383|                 xs[child] = tmp
384| 
385|                 root = child
386|                 # repeat to continue sifting down the child now...
387| 
388|             else:
389|                 # The root holds the largest element. Since we may
390|                 # assume the heaps rooted at the children are valid,
391|                 # this means that we are done.
392|                 return
393| 
394|     '''Build the heap so that largest value is at the root.'''
395|     # Find parent of last element (start = first leaf)...
396|     start = floor((len(xs)-2) / 2) + 1
397| 
398|     while 0 < start:
399|         stats[0] += 1
400| 
401|         # Look at next previous element...
402|         start -= 1
403| 
404|         # Sift the indexed node down to the proper place such that
405|         # all nodes below start are in heap order...
406|         sift_down(xs, start, len(xs))
407| 
408|     # The following loop maintains the invariants that xs[0:end-1]
409|     # is a heap, and every element xs[end:count-1] beyond end is
410|     # greater than everything before it, i.e. xs[end:count-1] is
411|     # in sorted order.
412|     end = len(xs)
413| 
414|     while 1 < end:
415|         # Heap size less one...
416|         end -= 1
417| 
418|         # xs[0] is the root and largest value.
419|         # The swap moves it in front of the sorted elements.
420|         tmp = xs[end]
421|         xs[end] = xs[0]
422|         xs[0] = tmp
423| 
424|         # The swap ruined the heap property, so restore it...
425|         sift_down(xs, 0, end)
426| 
427|     print(f'heapify-passes: {stats[0]}')
428|     print(f'sift-down-calls: {stats[1]}; sift-down-swaps: {stats[2]}')
429| 
430|     # Return list...
431|     return xs
432| 
433| if __name__ == '__main__':
434|     sortedNums = heapsort(list(RandNums))
435| 
436|     print(f'list-is-sorted: {list_is_sorted(sortedNums)}')
437|     print()
438| 
439| #:code::
440| from examples import RandNums, list_is_sorted
441| 
442| def quicksort (xs):
443|     '''QUICK SORT routine. [https://en.wikipedia.org/wiki/Quicksort]
443|        (Yes, it really is this simple.)
443|     '''

444|     print(f'Quick Sort ({len(xs)} items)')
445|     stats = [0, 0]
446| 
447|     def qsort (xs):
448|         '''Recursive quicksort function.'''
449|         stats[0] += 1
450| 
451|         # No need to sort single items or empty lists...
452|         if len(xs) < 2:
453|             return xs
454| 
455|         # If list has two items, simply compare them...
456|         if len(xs) == 2:
457|             if xs[0] < xs[1]:
458|                 # The two are already sorted...
459|                 return xs
460| 
461|             # The two are out of order, return reverse order...
462|             stats[1] += 1
463|             return [xs[1], xs[0]]
464| 
465|         # Pick an item from the list...
466|         # (Ideal would be to take the mean, but that requires an iteration.)
467|         # ((We might try a random point.))
468|         m = xs[0]
469| 
470|         # Divide list into two halves...
471|         smaller = [x for x in xs[1:] if x <= m]
472|         larger  = [x for x in xs[1:] if m < x]
473| 
474|         # Recurse on the halves and return the result...
475|         # NOTE THE DOUBLE RECURSION!
476|         return qsort(smaller)+[m]+qsort(larger)
477| 
478|     xs = qsort(xs)
479| 
480|     print(f'qsort-calls: {stats[0]}; qsort-swaps: {stats[1]}')
481| 
482|     # Return list...
483|     return xs
484| 
485| if __name__ == '__main__':
486|     sortedNums = quicksort(list(RandNums))
487| 
488|     print(f'list-is-sorted: {list_is_sorted(sortedNums)}')
489|     print()
490| 
491| #:code::
492| from examples import RandNums, list_is_sorted
493| 
494| def shellsort (xs):
495|     '''SHELL SORT. [https://en.wikipedia.org/wiki/Shellsort]'''
496|     print(f'Shell Sort ({len(xs)} items)')
497| 
498|     # Ciura gap sequence
499|     gaps = [701, 301, 132, 57, 23, 10, 4, 1]
500| 
501|     # Start with the largest gap and work down to a gap of 1
502|     # similar to insertion sort but instead of 1, gap is being
503|     # used in each step
504|     for gap in gaps:
505| 
506|         # Do a gapped insertion sort for every element in gaps
507|         # Each loop leaves a[0..gap-1] in gapped order
508|         for ix in range(gap, len(xs)):
509| 
510|             # Save xs[ix] in temp to make a hole at xs[ix]...
511|             tmp = xs[ix]
512| 
513|             # Shift earlier gap-sorted elements up to correct
514|             # location for xs[ix] is found
515|             jx = ix
516|             while (gap <= jx) and (tmp < xs[jx-gap]):
517|                 xs[jx] = xs[jx-gap]
518|                 jx -= gap
519| 
520|             # put temp (the original a[i]) in its correct location
521|             xs[jx] = tmp
522| 
523|     # Return list...
524|     return xs
525| 
526| if __name__ == '__main__':
527|     sortedNums = shellsort(list(RandNums))
528| 
529|     print(f'list-is-sorted: {list_is_sorted(sortedNums)}')
530|     print()
531| 
532| #:code::
533| 
534| #:end:code::
535|