2025-xx-xx_sort-routines-in-python.html
001|
002|
003|
004|
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|
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|
059|
060|
061|
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|
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|
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|
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]
106|
107| def sort_pass ():
108|
109| flag = False
110|
111|
112| for ix in range(len(xs)-1):
113|
114|
115| if xs[ix+1] < xs[ix]:
116|
117| stats[1] += 1
118|
119|
120| tmp = xs[ix]
121| xs[ix] = xs[ix+1]
122| xs[ix+1] = tmp
123|
124|
125| flag = True
126|
127|
128| return flag
129|
130|
131| while sort_pass():
132| stats[0] += 1
133|
134| print(f'passes: {stats[0]}; swaps: {stats[1]:,}')
135|
136|
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|
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]
152|
153| def sort_pass ():
154|
155| flag = False
156|
157|
158| for ix in range(len(xs)-1):
159|
160|
161| if xs[ix+1] < xs[ix]:
162|
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|
171| for ix in range(len(xs)-1, 1, -1):
172|
173|
174| if xs[ix] < xs[ix-1]:
175|
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|
184| return flag
185|
186|
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|
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|
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|
211| for ix in range(1, len(xs)):
212|
213|
214| jx = ix
215|
216|
217| while (0 < jx) and (xs[jx] < xs[jx-1]):
218|
219|
220|
221| swaps += 1
222|
223| tmp = xs[jx-1]
224| xs[jx-1] = xs[jx]
225| xs[jx] = tmp
226|
227|
228| jx -= 1
229|
230| print(f'total-swaps: {swaps:,}')
231|
232|
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|
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|
250| for ix in range(len(xs)):
251|
252|
253| mx = ix
254|
255|
256| for jx in range(ix+1, len(xs)):
257|
258| if xs[jx] < xs[mx]:
259|
260| mx = jx
261|
262|
263| if mx != ix:
264|
265|
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|
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|
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|
300| while (lx < len(left)) and (rx < len(right)):
301|
302|
303| if left[lx] <= right[rx]:
304|
305| buff.append(left[lx])
306|
307| lx += 1
308| else:
309|
310| buff.append(right[rx])
311|
312| rx += 1
313|
314|
315|
316| buff.extend(left[lx:])
317| buff.extend(right[rx:])
318|
319|
320| return buff
321|
322| def merge_sort (xs):
323| '''Recursive merge sort function.'''
324| calls[0] += 1
325|
326|
327| if len(xs) <= 1:
328| return xs
329|
330|
331| mid = len(xs) // 2
332|
333|
334|
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|
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|
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]
358|
359| left_child = lambda n: (2*n)+1
360|
361|
362|
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|
368| while left_child(root) < end:
369|
370|
371| child = left_child(root)
372|
373|
374| if (child+1 < end) and (xs[child] < xs[child+1]):
375| child += 1
376|
377| if xs[root] < xs[child]:
378|
379| stats[2] += 1
380|
381| tmp = xs[root]
382| xs[root] = xs[child]
383| xs[child] = tmp
384|
385| root = child
386|
387|
388| else:
389|
390|
391|
392| return
393|
394| '''Build the heap so that largest value is at the root.'''
395|
396| start = floor((len(xs)-2) / 2) + 1
397|
398| while 0 < start:
399| stats[0] += 1
400|
401|
402| start -= 1
403|
404|
405|
406| sift_down(xs, start, len(xs))
407|
408|
409|
410|
411|
412| end = len(xs)
413|
414| while 1 < end:
415|
416| end -= 1
417|
418|
419|
420| tmp = xs[end]
421| xs[end] = xs[0]
422| xs[0] = tmp
423|
424|
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|
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|
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|
452| if len(xs) < 2:
453| return xs
454|
455|
456| if len(xs) == 2:
457| if xs[0] < xs[1]:
458|
459| return xs
460|
461|
462| stats[1] += 1
463| return [xs[1], xs[0]]
464|
465|
466|
467|
468| m = xs[0]
469|
470|
471| smaller = [x for x in xs[1:] if x <= m]
472| larger = [x for x in xs[1:] if m < x]
473|
474|
475|
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|
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|
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|
499| gaps = [701, 301, 132, 57, 23, 10, 4, 1]
500|
501|
502|
503|
504| for gap in gaps:
505|
506|
507|
508| for ix in range(gap, len(xs)):
509|
510|
511| tmp = xs[ix]
512|
513|
514|
515| jx = ix
516| while (gap <= jx) and (tmp < xs[jx-gap]):
517| xs[jx] = xs[jx-gap]
518| jx -= gap
519|
520|
521| xs[jx] = tmp
522|
523|
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|
533|
534|
535|