python: Algorithms

 

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
# encoding: utf-8
# 版权所有 2023 ©涂聚文有限公司
# 许可信息查看:Huffman Coding  Huffman Coding  霍夫曼编码 ( Huffman coding ) 是一种可变长的前缀码
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 311
# Datetime  : 2023/9/27 8:47
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : NodeTree.py
# explain   : 学习
 
class NodeTree(object):
    """
    Huffman Coding  霍夫曼编码
    """
 
    def __init__(self, left=None, right=None):
        """
 
        :param left:
        :param right:
        """
        self.left = left
        self.right = right
 
    def children(self):
        """
 
        :return:
        """
        return (self.left, self.right)
 
    def nodes(self):
        """
 
        :return:
        """
        return (self.left, self.right)
 
    def __str__(self):
        """
 
        :return:
        """
        return '%s_%s' % (self.left, self.right)

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# encoding: utf-8
# 版权所有 2023 ©涂聚文有限公司
# 许可信息查看:
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 311
# Datetime  : 2023/9/27 12:45
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : DuNode.py
# explain   : 学习
 
class DuNode(object):
    """
 
    """
    def __init__(self, item=0):
        self.key = item
        self.left, self.right = None, None

  

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
# encoding: utf-8
# 版权所有 2023 ©涂聚文有限公司
# 许可信息查看:
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 311
# Datetime  : 2023/9/27 12:21
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : Person.py
# explain   : 学习
 
class Person:
    """
    实体类
    """
    def __init__(self, id:int, salary:float,realname:str):
        """
 
        :param id:
        :param salary:
        :param realname
        """
        self.id = id
        self.salary = salary
        self.realname=realname
        self.someBigObject = object()
 
    @property
    def Id(self):
        """
 
        :return:
        """
        return self.id
 
    @Id.setter
    def Id(self,id):
        """
 
        :param id:
        :return:
        """
        self.id=id
 
 
    @property
    def Salary(self):
        """
 
        :return:
        """
 
        return self.salary
 
    @Salary.setter
    def Salary(self,salary):
        """
 
        :param salary:
        :return:
        """
        self.salary = salary
 
 
    @property
    def RealName(self):
        """
 
        :return:
        """
        return self.realname
 
    @RealName.setter
    def RealNmae(self,realname):
        """
 
        :param realname:
        :return:
        """
        self.realname = realname
 
    def __str__(self):
        """
 
        :return:
        """
 
        return "Person{" + "id=" + str(self.id) + ", salary=" + str(self.salary) +",realname="+self.realname+ ", someBigObject=" + str(
            self.someBigObject) + "}"

  

 

 

 

 

 

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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
# encoding: utf-8
# 版权所有 2023 ©涂聚文有限公司
# 许可信息查看:
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 311
# Datetime  : 2023/9/26 10:07
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : SortingAlgorithms.py
# explain   : 学习
 
import tkinter as tk
from tkinter import ttk
import itertools
import math
import sys
import os
from typing import List
import random
import threading
import time
import ChapterOne.Person
import ChapterOne.DuNode
from typing import List, TypeVar
 
class SortingAlgorithms(object):
    """
    排序算法
    """
 
    def BubbleSort(array: list):
        """
        1。Bubble Sort冒泡排序法
        :param array int数组
        :return:
        """
        # loop to access each array element
        for i in range(len(array)):
 
            # loop to compare array elements
            for j in range(0, len(array) - i - 1):
 
                # compare two adjacent elements
                # change > to < to sort in descending order
                if array[j] > array[j + 1]:
                    # swapping elements if elements
                    # are not in the intended order
                    temp = array[j]
                    array[j] = array[j + 1]
                    array[j + 1] = temp
 
    def BubbleSort2(array: list):
        """
        1。Bubble Sort冒泡排序法
        :param array int数组
        :return:
        """
 
        # loop through each element of array
        for i in range(len(array)):
 
            # keep track of swapping
            swapped = False
 
            # loop to compare array elements
            for j in range(0, len(array) - i - 1):
 
                # compare two adjacent elements
                # change > to < to sort in descending order
                if array[j] > array[j + 1]:
                    # swapping occurs if elements
                    # are not in the intended order
                    temp = array[j]
                    array[j] = array[j + 1]
                    array[j + 1] = temp
 
                    swapped = True
 
            # no swapping means the array is already sorted
            # so no need for further comparison
            if not swapped:
                break
 
    def SelectionSort(array: list):
        """
        2 python Program for Selection Sort 选择排序
        :param array int数组
        :return:
        """
        for i in range(len(array)):
            # Find the minimum element in remaining
            # unsorted array
            min_idx = i
            for j in range(i + 1, len(array)):
                if array[min_idx] > array[j]:
                    min_idx = j
 
            # Swap the found minimum element with
            # the first element
            array[i], array[min_idx] = array[min_idx], array[i]
 
    def InsertionSort(array: list):
        """
        3 Insertion Sort插入排序
        :param array int数组
        :return:
        """
        # Traverse through 1 to len(arr)
        for i in range(1, len(array)):
 
            key = array[i]
 
            # Move elements of arr[0..i-1], that are
            # greater than key, to one position ahead
            # of their current position
            j = i - 1
            while j >= 0 and key < array[j]:
                array[j + 1] = array[j]
                j -= 1
            array[j + 1] = key
 
    def Partition(array, low, high):
        """
        :param array int数组
        :param low:
        :param high:
        :return:
        """
        # Choose the rightmost element as pivot
        pivot = array[high]
 
        # Pointer for greater element
        i = low - 1
 
        # Traverse through all elements
        # compare each element with pivot
        for j in range(low, high):
            if array[j] <= pivot:
                # If element smaller than pivot is found
                # swap it with the greater element pointed by i
                i = i + 1
 
                # Swapping element at i with element at j
                (array[i], array[j]) = (array[j], array[i])
 
        # Swap the pivot element with
        # the greater element specified by i
        (array[i + 1], array[high]) = (array[high], array[i + 1])
 
        # Return the position from where partition is done
        return i + 1
 
    def QuickSort(array, low, high):
        """
        4 Quick Sort 快速排序
        :param array int数组
        :param low:
        :param high:
        :return:
        """
        if low < high:
            # Find pivot element such that
            # element smaller than pivot are on the left
            # element greater than pivot are on the right
            pi = SortingAlgorithms.Partition(array, low, high)
 
            # Recursive call on the left of pivot
            SortingAlgorithms.QuickSort(array, low, pi - 1)
 
            # Recursive call on the right of pivot
            SortingAlgorithms.QuickSort(array, pi + 1, high)
 
    def MergeSort(array: list):
        """
        5 Merge Sort 合并/归并排序
        :param array int数组
        :return:
        """
        if len(array) > 1:
 
            # Finding the mid of the array
            mid = len(array) // 2
 
            # Dividing the array elements
            L = array[:mid]
 
            # Into 2 halves
            R = array[mid:]
 
            # Sorting the first half
            SortingAlgorithms.MergeSort(L)
 
            # Sorting the second half
            SortingAlgorithms.MergeSort(R)
 
            i = j = k = 0
 
            # Copy data to temp arrays L[] and R[]
            while i < len(L) and j < len(R):
                if L[i] <= R[j]:
                    array[k] = L[i]
                    i += 1
                else:
                    array[k] = R[j]
                    j += 1
                k += 1
 
            # Checking if any element was left
            while i < len(L):
                array[k] = L[i]
                i += 1
                k += 1
 
            while j < len(R):
                array[k] = R[j]
                j += 1
                k += 1
 
    def CountingSort(array: list, hight: int):
        """
        6 Counting Sort 计数排序
        :param array int数组
        :param hight 最大的整数 如100,数组中必须小数此数的整数
        :return:
        """
        size = len(array)
        output = [0] * size
 
        # Initialize count array
        dcount = [0] * hight
 
        # Store the count of each elements in count array
        print(size)
        for i in range(0, size):
            dcount[array[i]] += 1
 
        # Store the cummulative count 最大的数
        for i in range(1, hight):
            dcount[i] += dcount[i - 1]
 
        # Find the index of each element of the original array in count array
        # place the elements in output array
        i = size - 1
        while i >= 0:
            output[dcount[array[i]] - 1] = array[i]
            dcount[array[i]] -= 1
            i -= 1
 
        # Copy the sorted elements into original array
        for i in range(0, size):
            array[i] = output[i]
 
    def CountingSortTo(array: List[int]):
        """
        6 Counting Sort 计数排序
        :param
        :return:
        """
        max = min = 0
        for i in array:
            if i < min:
                min = i
            if i > max:
                max = i
        count = [0] * (max - min + 1)
        for j in range(max - min + 1):
            count[j] = 0
        for index in array:
            count[index - min] += 1
        index = 0
        for a in range(max - min + 1):
            for c in range(count[a]):
                array[index] = a + min
                index += 1
 
    def countingSort(array, exp1):
        """
 
        :param array
        :param exp1:
        :return:
        """
 
        n = len(array)
 
        # The output array elements that will have sorted arr
        output = [0] * (n)
 
        # initialize count array as 0
        count = [0] * (10)
 
        # Store count of occurrences in count[]
        for i in range(0, n):
            index = array[i] // exp1
            count[index % 10] += 1
 
        # Change count[i] so that count[i] now contains actual
        # position of this digit in output array
        for i in range(1, 10):
            count[i] += count[i - 1]
 
        # Build the output array
        i = n - 1
        while i >= 0:
            index = array[i] // exp1
            output[count[index % 10] - 1] = array[i]
            count[index % 10] -= 1
            i -= 1
 
        # Copying the output array to arr[],
        # so that arr now contains sorted numbers
        i = 0
        for i in range(0, len(array)):
            array[i] = output[i]
 
    def RadixSort(array: list):
        """
        7 Radix Sort 基数排序
        :param array
        :return:
        """
        # Find the maximum number to know number of digits
        max1 = max(array)
 
        # Do counting sort for every digit. Note that instead
        # of passing digit number, exp is passed. exp is 10^i
        # where i is current digit number
        exp = 1
        while max1 / exp >= 1:
            SortingAlgorithms.countingSort(array, exp)
            exp *= 10
 
    def insertionSort(array: list):
        """
 
        :return:
        """
        for i in range(1, len(array)):
            up = array[i]
            j = i - 1
            while j >= 0 and array[j] > up:
                array[j + 1] = array[j]
                j -= 1
            array[j + 1] = up
        return array
 
    def BucketSort(array):
        """
        8 Bucket Sort 桶排序
        :param array
        :return:
        """
        arr = []
        slot_num = 10  # 10 means 10 slots, each
        # slot's size is 0.1
        for i in range(slot_num):
            arr.append([])
 
        # Put array elements in different buckets
        for j in array:
            index_b = int(slot_num * j)
            arr[index_b].append(j)
 
        # Sort individual buckets
        for i in range(slot_num):
            arr[i] = SortingAlgorithms.insertionSort(arr[i])
 
        # concatenate the result
        k = 0
        for i in range(slot_num):
            for j in range(len(arr[i])):
                array[k] = arr[i][j]
                k += 1
        return array
 
    # Bucket Sort in Python
 
    def BucketSortTo(array: list):
        """
         8 Bucket Sort 桶排序
        :param array
        :return:
        """
        bucket = []
 
        # Create empty buckets
        for i in range(len(array)):
            bucket.append([])
 
        # Insert elements into their respective buckets
        for j in array:
            index_b = int(10 * j)
            bucket[index_b].append(j)
 
        # Sort the elements of each bucket
        for i in range(len(array)):
            bucket[i] = sorted(bucket[i])
 
        # Get the sorted elements
        k = 0
        for i in range(len(array)):
            for j in range(len(bucket[i])):
                array[k] = bucket[i][j]
                k += 1
        return array
 
    def heapify(array: list, Nsize: int, index: int):
        """
 
        :param array 数组
        :param Nsize: 数组长度
        :param index: 索引号
        :return:
        """
        largest = index  # Initialize largest as root
        l = 2 * index + 1  # left = 2*i + 1
        r = 2 * index + 2  # right = 2*i + 2
 
        # See if left child of root exists and is
        # greater than root
        if l < Nsize and array[largest] < array[l]:
            largest = l
 
        # See if right child of root exists and is
        # greater than root
        if r < Nsize and array[largest] < array[r]:
            largest = r
 
        # Change root, if needed
        if largest != index:
            array[index], array[largest] = array[largest], array[index]  # swap
 
            # Heapify the root.
            SortingAlgorithms.heapify(array, Nsize, largest)
 
    # The main function to sort an array of given size
 
    def HeapSort(array: list):
        """
        9 Heap Sort 堆排序
        :param array
        :return:
        """
 
        Nsize = len(array)
 
        # Build a maxheap.
        for i in range(Nsize // 2 - 1, -1, -1):
            SortingAlgorithms.heapify(array, Nsize, i)
 
        # One by one extract elements
        for i in range(Nsize - 1, 0, -1):
            array[i], array[0] = array[0], array[i]  # swap
            SortingAlgorithms.heapify(array, i, 0)
 
    def ShellSort(array: list):
        """
        10 Shell Sort 希尔排序
        :param array 数组
        :return:
        """
        # code here
        nszie = len(array)
 
        gap = nszie // 2
 
        while gap > 0:
            j = gap
            # Check the array in from left to right
            # Till the last possible index of j
            while j < nszie:
                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 array[i + gap] > array[i]:
 
                        break
                    else:
                        array[i + gap], array[i] = array[i], array[i + gap]
 
                    i = i - gap  # To check left side also
                    # If the element present is greater than current element
                j += 1
            gap = gap // 2
 
    def LinearSearch(array: list, fint: int):
        """
        11 Linear Search线性搜索
        :param array 整数数组
        :param fint 要查找的数字
        :return:
        """
        nsize = len(array)
        # Going through array sequencially
        for i in range(0, nsize):
            if (array[i] == fint):
                return # 找到了
        return -1  # 未找到
 
    def BinarySearch(array: list, x, low, high):
        """
        12 Binary Search  二分查找
        :param x:要搜索的数字
        :param low:
        :param high:
        :return:
        """
 
        if high >= low:
 
            mid = low + (high - low) // 2
 
            # If found at mid, then return it
            if array[mid] == x:
                return mid
 
            # Search the left half
            elif array[mid] > x:
                return SortingAlgorithms.BinarySearch(array, x, low, mid - 1)
 
            # Search the right half
            else:
                return SortingAlgorithms.BinarySearch(array, x, mid + 1, high)
 
        else:
            return -1
 
    def BingoSort(array:list, size:int):
        """
        13 Bingo Sort宾果排序
        :param array 整型数组
        :param size: 数组长度
        :return:
        """
 
        # Finding the smallest element From the Array
        bingo = min(array)
 
        # Finding the largest element from the Array
        largest = max(array)
        nextBingo = largest
        nextPos = 0
        while bingo < nextBingo:
 
            # Will keep the track of the element position to
            # shifted to their correct position
            startPos = nextPos
            for i in range(startPos, size):
                if array[i] == bingo:
                    array[i], array[nextPos] = array[nextPos], array[i]
                    nextPos += 1
 
                #  Here we are finding the next Bingo Element
                #  for the next pass
                elif array[i] < nextBingo:
                    nextBingo = array[i]
            bingo = nextBingo
            nextBingo = largest
 
 
    def TimcalcMinRun(nszie: int):
        """
 
        :param n
        :return:
        """
        """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, ...
        """
        MIN_MERGE = 32
        r = 0
 
        while nszie >= MIN_MERGE:
            r |= nszie & 1
            nszie >>= 1
        print(nszie)
        return nszie + r
 
        # This function sorts array from left index to
        # to right index which is of size atmost RUN
 
 
    def TiminsertionSort(array, left, right):
        """
 
        :param array
        :param left:
        :param right:
        :return:
        """
        for i in range(left + 1, right + 1):
            j = i
            while j > left and array[j] < array[j - 1]:
                array[j], array[j - 1] = array[j - 1], array[j]
                j -= 1
 
        # Merge function merges the sorted runs
 
 
    def Timmerge(array, l, m, r):
        """
 
        :param array
        :param l:
        :param m:
        :param r:
        :return:
        """
 
        # 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(array[l + i])
        for i in range(0, len2):
            right.append(array[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]:
                array[k] = left[i]
                i += 1
 
            else:
                array[k] = right[j]
                j += 1
 
            k += 1
 
        # Copy remaining elements of left, if any
        while i < len1:
            array[k] = left[i]
            k += 1
            i += 1
 
        # Copy remaining element of right, if any
        while j < len2:
            array[k] = right[j]
            k += 1
            j += 1
 
        # Iterative Timsort function to sort the
        # array[0...n-1] (similar to merge sort)
 
 
    def TimSort(array):
        """
        14 Tim Sort
        :param array
        :return:
        """
        n = len(array)
        minRun = SortingAlgorithms.TimcalcMinRun(n)
 
        # Sort individual subarrays of size RUN
        for start in range(0, n, minRun):
            end = min(start + minRun - 1, n - 1)
            SortingAlgorithms.TiminsertionSort(array, 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:
                    SortingAlgorithms.Timmerge(array, left, mid, right)
 
            size = 2 * size
 
 
    def getNextGap(gap):
        # Shrink gap by Shrink factor
        gap = (gap * 10) // 13
        if gap < 1:
            return 1
        return gap
 
        # Function to sort arr[] using Comb Sort
 
 
    def CombSort(array):
        """
        15  Comb Sort
        :param array
        :return:
        """
        n = len(array)
 
        # Initialize gap
        gap = n
 
        # Initialize swapped as true to make sure that
        # loop runs
        swapped = True
 
        # Keep running while gap is more than 1 and last
        # iteration caused a swap
        while gap != 1 or swapped == 1:
 
            # Find next gap
            gap = SortingAlgorithms.getNextGap(gap)
 
            # Initialize swapped as false so that we can
            # check if swap happened or not
            swapped = False
 
            # Compare all elements with current gap
            for i in range(0, n - gap):
                if array[i] > array[i + gap]:
                    array[i], array[i + gap] = array[i + gap], array[i]
                    swapped = True
 
 
    def PigeonholeSort(array):
        """
        16  Pigeonhole Sort 鸽巢排序
        :param array
        :return:
        """
        # size of range of values in the list
        # (ie, number of pigeonholes we need)
        my_min = min(array)
        my_max = max(array)
        size = my_max - my_min + 1
 
        # our list of pigeonholes
        holes = [0] * size
 
        # Populate the pigeonholes.
        for x in array:
            assert type(x) is int, "integers only please"
            holes[x - my_min] += 1
 
        # Put the elements back into the array in order.
        i = 0
        for count in range(size):
            while holes[count] > 0:
                holes[count] -= 1
                array[i] = count + my_min
                i += 1
 
 
    def CycleSort(array):
        """
        17 Cycle Sort 循环排序
        :param array
        :return:
        """
        writes = 0
 
        # Loop through the array to find cycles to rotate.
        for cycleStart in range(0, len(array) - 1):
            item = array[cycleStart]
 
            # Find where to put the item.
            pos = cycleStart
            for i in range(cycleStart + 1, len(array)):
                if array[i] < item:
                    pos += 1
 
            # If the item is already there, this is not a cycle.
            if pos == cycleStart:
                continue
 
            # Otherwise, put the item there or right after any duplicates.
            while item == array[pos]:
                pos += 1
            array[pos], item = item, array[pos]
            writes += 1
 
            # Rotate the rest of the cycle.
            while pos != cycleStart:
 
                # Find where to put the item.
                pos = cycleStart
                for i in range(cycleStart + 1, len(array)):
                    if array[i] < item:
                        pos += 1
 
                # Put the item there or right after any duplicates.
                while item == array[pos]:
                    pos += 1
                array[pos], item = item, array[pos]
                writes += 1
 
        return writes
 
 
    def CocktailSort(array):
        """
        18 Cocktail Sort 鸡尾酒排序
        :param array
        :return:
        """
        n = len(array)
        swapped = True
        start = 0
        end = n - 1
        while (swapped == True):
 
            # reset the swapped flag on entering the loop,
            # because it might be true from a previous
            # iteration.
            swapped = False
 
            # loop from left to right same as the bubble
            # sort
            for i in range(start, end):
                if (array[i] > array[i + 1]):
                    array[i], array[i + 1] = array[i + 1], array[i]
                    swapped = True
 
            # if nothing moved, then array is sorted.
            if (swapped == False):
                break
 
            # otherwise, reset the swapped flag so that it
            # can be used in the next stage
            swapped = False
 
            # move the end point back by one, because
            # item at the end is in its rightful spot
            end = end - 1
 
            # from right to left, doing the same
            # comparison as in the previous stage
            for i in range(end - 1, start - 1, -1):
                if (array[i] > array[i + 1]):
                    array[i], array[i + 1] = array[i + 1], array[i]
                    swapped = True
 
            # increase the starting point, because
            # the last stage would have moved the next
            # smallest number to its rightful spot.
            start = start + 1
 
 
    def StrandSort(array):
        """
        19 Strand Sort 经典排序
        :param array
        :return:
        """
        output = SortingAlgorithms.strand(array)
        while len(array):
            output = SortingAlgorithms.Strandmerge(output, SortingAlgorithms.strand(array))
        return output
 
 
    def strand(array):
        """
 
        :param array
        :return:
        """
 
        element, sub = 0, [array.pop(0)]
        while element < len(array):
            if array[element] > sub[-1]:
                sub.append(array.pop(element))
            else:
                element += 1
        return sub
 
 
    def Strandmerge(array, arrayb):
        """
 
        :param array
        :param arrayb:
        :return:
        """
        output = []
        while len(array) and len(arrayb):
            if array[0] < arrayb[0]:
                output.append(array.pop(0))
            else:
                output.append(arrayb.pop(0))
        output += array
        output += arrayb
        return output
 
 
    def compAndSwap(array, i, j, dire):
        """
 
        :param i:
        :param j:
        :param dire:
        :return:
        """
        if (dire == 1 and array[i] > array[j]) or (dire == 0 and array[i] < array[j]):
            array[i], array[j] = array[j], array[i]
 
        # It recursively sorts a bitonic sequence in ascending order,
        # if dir = 1, and in descending order otherwise (means dir=0).
        # The sequence to be sorted starts at index position low,
        # the parameter cnt is the number of elements to be sorted.
 
 
    def bitonicMerge(array, low, cnt, dire):
        """
 
        :param low:
        :param cnt:
        :param dire:
        :return:
        """
 
        if cnt > 1:
            k = cnt // 2
            for i in range(low, low + k):
                SortingAlgorithms.compAndSwap(array, i, i + k, dire)
            SortingAlgorithms.bitonicMerge(array, low, k, dire)
            SortingAlgorithms.bitonicMerge(array, low + k, k, dire)
 
        # Caller of bitonicSort for sorting the entire array of length N
        # in ASCENDING order
 
 
    def BitonicSort(array, N, up):
        """
 
        :param N:
        :param up:
        :return:
        """
        SortingAlgorithms.bSort(array, 0, N, up)
 
        # This function first produces a bitonic sequence by recursively
        # sorting its two halves in opposite sorting orders, and then
        # calls bitonicMerge to make them in the same order
 
 
    def bSort(array, low, cnt, dire):
        """
        20  Bitonic Sort 双调排序
 
        :param low:
        :param cnt:
        :param dire:
        :return:
        """
 
        if cnt > 1:
            k = cnt // 2
            SortingAlgorithms.bSort(array, low, k, 1)
            SortingAlgorithms.bSort(array, low + k, k, 0)
            SortingAlgorithms.bitonicMerge(array, low, cnt, dire)
 
 
    def flip(array, i):
        """
 
        :param array
        :param i:
        :return:
        """
        start = 0
        while start < i:
            temp = array[start]
            array[start] = array[i]
            array[i] = temp
            start += 1
            i -= 1
 
        # Returns index of the maximum
        # element in arr[0..n-1] */
 
 
    def findMax(array, n):
        """
 
        :param array
        :param n:
        :return:
        """
        mi = 0
        for i in range(0, n):
            if array[i] > array[mi]:
                mi = i
        return mi
 
        # The main function that
        # sorts given array
        # using flip operations
 
 
    def PancakeSort(array, n):
        """
        21 Pancake Sort 煎饼排序.
        :param n:
        :return:
        """
 
        # Start from the complete
        # array and one by one
        # reduce current size
        # by one
        curr_size = n
        while curr_size > 1:
            # Find index of the maximum
            # element in
            # arr[0..curr_size-1]
            mi = SortingAlgorithms.findMax(array, curr_size)
 
            # Move the maximum element
            # to end of current array
            # if it's not already at
            # the end
            if mi != curr_size - 1:
                # To move at the end,
                # first move maximum
                # number to beginning
                SortingAlgorithms.flip(array, mi)
 
                # Now move the maximum
                # number to end by
                # reversing current array
                SortingAlgorithms.flip(array, curr_size - 1)
            curr_size -= 1
 
    def BogoSort(array:list):
        """
         22 Bogo Sort  BogoSort or Permutation Sort 置换排序、愚蠢排序、慢排序、猎枪排序或猴子排序
        :param array
        :return:
        """
        n = len(array)
        while (SortingAlgorithms.BogoisSorted(array) == False):
            SortingAlgorithms.BogoShuffle(array)
 
 
    # To check if array is sorted or not
    def BogoisSorted(array):
        """
 
        :param array
        :return:
        """
        n = len(array)
        for i in range(0, n - 1):
            if (array[i] > array[i + 1]):
                return False
        return True
 
    # To generate permutation of the array
 
    def BogoShuffle(array):
        """
 
        :param array
        :return:
        """
        n = len(array)
        for i in range(0, n):
            r = random.randint(0, n - 1)
            array[i], array[r] = array[r], array[i]
 
    def GnomeSort(array:list):
        """
        23 Gnome Sort 地精排序,也称侏儒排序
        :param array:
        :return:
        """
        nsize=len(array)
        index = 0
        while index < nsize:
            if index == 0:
                index = index + 1
            if array[index] >= array[index - 1]:
                index = index + 1
            else:
                array[index], array[index - 1] = array[index - 1], array[index]
                index = index - 1
 
        return array
 
    def SleepRoutine(num):
        """
 
        :param num
        :return:
        """
        # Sleeping time is proportional to the number
 
        time.sleep(num / 1000.0# Sleep for 'num' milliseconds
        print(num, end=" ")
 
    # A function that performs sleep sort
    def SleepSort(array:list):
        """
        24.Sleep Sort 睡眠排序
        :param array
        :return:
        """
        threads = []
 
        # Create a thread for each element in the input array
        for num in array:
            thread = threading.Thread(target=SortingAlgorithms.SleepRoutine, args=(num,))
            threads.append(thread)
            thread.start()
 
        # Wait for all threads to finish
        for thread in threads:
            thread.join()
 
    def StoogeSort(array:list, low:int, hight:int):
        """
         25 Stooge Sort 臭皮匠排序
        :param array 数组
        :param low: 起始索此 0 开始
        :param hight: 数组长度-1
        :return:
        """
        if low >= hight:
            return
 
        # If first element is smaller
        # than last, swap them
        if array[low] > array[hight]:
            t = array[low]
            array[low] = array[hight]
            array[hight] = t
 
        # If there are more than 2 elements in
        # the array
        if hight - low + 1 > 2:
            t = (int)((hight - low + 1) / 3)
 
            # Recursively sort first 2 / 3 elements
            SortingAlgorithms.StoogeSort(array, low, (hight - t))
 
            # Recursively sort last 2 / 3 elements
            SortingAlgorithms.StoogeSort(array, low + t, (hight))
 
            # Recursively sort first 2 / 3 elements
            # again to confirm
            SortingAlgorithms.StoogeSort(array, low, (hight - t))
 
 
    def TagSort(persons:List[ChapterOne.Person.Person], tag:list):
        """
        26 Tag Sort (To get both sorted and original)
        :param persons
        :param tag:
        :return:
        """
 
        n = len(persons)
        for i in range(n):
            for j in range(i+1, n):
                if persons[tag[i]].Salary > persons[tag[j]].Salary:
                    # Note we are not sorting the actual Persons array, but only the tag array
                    tag[i], tag[j] = tag[j], tag[i]
 
    global root
    root = ChapterOne.DuNode.DuNode()
    root = None
    # This method mainly
    # calls insertRec()
    def insert(key):
        global root
        root = SortingAlgorithms.insertRec(root, key)
 
    # A recursive function to
    # insert a new key in BST
    def insertRec(root, key):
 
        # If the tree is empty,
        # return a new node
 
        if (root == None):
            root = ChapterOne.DuNode.DuNode(key)
            return root
        #print(root)
        # Otherwise, recur
        # down the tree
        if (key < root.key):
            root.left = SortingAlgorithms.insertRec(root.left, key)
        elif (key > root.key):
            root.right = SortingAlgorithms.insertRec(root.right, key)
 
        #print(root)
 
        # return the root
        return root
 
    # A function to do
    # inorder traversal of BST
    def inorderRec(root):
        """
 
        :return:
        """
        if (root != None):
            SortingAlgorithms.inorderRec(root.left)
            print(root.key, end=" ")
            SortingAlgorithms.inorderRec(root.right)
 
    def treeins(array):
        """
        27 Tree Sort
        :return:
        """
        for i in range(len(array)):
            SortingAlgorithms.insert(array[i])
 
    def treedemo(array):
        """
        27 Tree Sort
        :return:
        """
        global root
        SortingAlgorithms.treeins(array)
        SortingAlgorithms.inorderRec(root)
 
    def BrickSort(array):
        """
        28.Brick Sort / Odd-Even Sort 砖排序算法(Brick Sort),也被称为奇偶排序(Odd-Even Sort)
        :param array:
        :return:
        """
        # Initially array is unsorted
        n=len(array)
        isSorted = 0
        while isSorted == 0:
            isSorted = 1
            temp = 0
            for i in range(1, n - 1, 2):
                if array[i] > array[i + 1]:
                    array[i], array[i + 1] = array[i + 1], array[i]
                    isSorted = 0
 
            for i in range(0, n - 1, 2):
                if array[i] > array[i + 1]:
                    array[i], array[i + 1] = array[i + 1], array[i]
                    isSorted = 0
 
        return array
 
 
    def WayMerge(gArray, low, mid1, mid2, high, destArray):
        """
        29.3-way Merge Sort
        :param low:
        :param mid1:
        :param mid2:
        :param high:
        :param destArray:
        :return:
        """
        i = low
        j = mid1
        k = mid2
        l = low
 
        # Choose smaller of the smallest in the three ranges
        while ((i < mid1) and (j < mid2) and (k < high)):
            if (gArray[i] < gArray[j]):
                if (gArray[i] < gArray[k]):
                    destArray[l] = gArray[i]
                    l += 1
                    i += 1
                else:
                    destArray[l] = gArray[k]
                    l += 1
                    k += 1
            else:
                if (gArray[j] < gArray[k]):
                    destArray[l] = gArray[j]
                    l += 1
                    j += 1
                else:
                    destArray[l] = gArray[k]
                    l += 1
                    k += 1
 
        # Case where first and second ranges
        # have remaining values
        while ((i < mid1) and (j < mid2)):
            if (gArray[i] < gArray[j]):
                destArray[l] = gArray[i]
                l += 1
                i += 1
            else:
                destArray[l] = gArray[j]
                l += 1
                j += 1
 
        # case where second and third ranges
        # have remaining values
        while ((j < mid2) and (k < high)):
            if (gArray[j] < gArray[k]):
                destArray[l] = gArray[j]
                l += 1
                j += 1
            else:
                destArray[l] = gArray[k]
                l += 1
                k += 1
 
        # Case where first and third ranges have
        # remaining values
        while ((i < mid1) and (k < high)):
            if (gArray[i] < gArray[k]):
                destArray[l] = gArray[i]
                l += 1
                i += 1
            else:
                destArray[l] = gArray[k]
                l += 1
                k += 1
 
        # Copy remaining values from the first range
        while (i < mid1):
            destArray[l] = gArray[i]
            l += 1
            i += 1
 
        # Copy remaining values from the second range
        while (j < mid2):
            destArray[l] = gArray[j]
            l += 1
            j += 1
 
        # Copy remaining values from the third range
        while (k < high):
            destArray[l] = gArray[k]
            l += 1
            k += 1
 
    def mergeSort3WayRec(gArray, low, high, destArray):
        """
 
        :param low:
        :param high:
        :param destArray:
        :return:
        """
        # If array size is 1 then do nothing
        if (high - low < 2):
            return
 
        # Splitting array into 3 parts
        mid1 = low + ((high - low) // 3)
        mid2 = low + 2 * ((high - low) // 3) + 1
 
        # Sorting 3 arrays recursively
        SortingAlgorithms.mergeSort3WayRec(destArray, low, mid1, gArray)
        SortingAlgorithms.mergeSort3WayRec(destArray, mid1, mid2, gArray)
        SortingAlgorithms.mergeSort3WayRec(destArray, mid2, high, gArray)
 
        # Merging the sorted arrays
        SortingAlgorithms.WayMerge(destArray, low, mid1, mid2, high, gArray)
 
    def MergeSort3Way(gArray):
        """
        29. 3-way Merge Sort 3路归并排序
        :param gArray:
        :return:
        """
        n=len(gArray)
        # if array size is zero return null
        if (n == 0):
            return
 
        # creating duplicate of given array
        fArray = []
 
        # copying elements of given array into
        # duplicate array
        fArray = gArray.copy()
 
        # sort function
        SortingAlgorithms.mergeSort3WayRec(fArray, 0, n, gArray)
 
        # copy back elements of duplicate array
        # to given array
        gArray = fArray.copy()
 
        # return the sorted array
        return gArray

  

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
# encoding: utf-8
# 版权所有 2023 ©涂聚文有限公司
# 许可信息查看:
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 311
# Datetime  : 2023/9/26 10:09
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : SortExample.py
# explain   : 学习
 
import ChapterOne.SortingAlgorithms
import ChapterOne.Person
import ChapterOne.DuNode
 
 
 
class Example(object):
    """"
    实例
    """
 
    def Bubble(self):
        """
         1。Bubble Sort冒泡排序法
        :return:
        """
        data = [-2, 45, 0, 11, -9]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.BubbleSort(data)
        print('\n1 冒泡排序法 Bubble Sorted Array in Ascending Order:')
        for i in range(len(data)):
            print("%d" % data[i], end=" ")
 
    def Select(self):
        """
        2 Selection Sort 选择排序
 
        :return:
        """
        geovindu = [64, 25, 12, 22, 11]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.SelectionSort(geovindu)
        print("\n2 选择排序Selection Sorted ")
        for i in range(len(geovindu)):
            print("%d" % geovindu[i], end=" ")
 
    def Insert(self):
        """
        3 Insertion Sort插入排序
        :return:
        """
        arr = [12, 11, 13, 5, 6]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.InsertionSort(arr)
        print("\n3 插入排序 Insertion Sorted ")
        for i in range(len(arr)):
            print("% d" % arr[i], end=" ")
 
    def Quick(self):
        """
        4 Quick Sort 快速排序
        :return:
        """
        array = [10, 7, 8, 9, 1, 5]
        N = len(array)
        # Function call
        ChapterOne.SortingAlgorithms.SortingAlgorithms.QuickSort(array, 0, N - 1)
        print("\n4 快速排序 Quick Sorted ")
        for x in array:
            print(x, end=" ")
 
    def Merge(self):
        """
        5 Merge Sort  合并/归并排序
        :return:
        """
        geovindu = [12, 11, 99, 13, 5, 6, 7, 88, 100]
 
        ChapterOne.SortingAlgorithms.SortingAlgorithms.MergeSort(geovindu)
        print("\n5 合并/归并排序 Merge Sorted ")
        for x in geovindu:
            print(x, end=" ")
 
    def Counting(self):
        """
        6 Counting Sort 计数排序
        :return:
        """
        geovindu = [17, 56, 71, 38, 61, 62, 48, 28, 57, 42]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.CountingSortTo(geovindu)
 
        print("\n6 计数排序  Counting Sorted ")
        print(geovindu)
        for i in range(0, len(geovindu)):
            print("% d" % geovindu[i], end=" ")
 
        geovindu = [4, 55, 22, 98, 9, 43, 11]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.CountingSort(geovindu, 100)
        print("\n6 计数排序  Counting Sorted ")
        for x in geovindu:
            print(x, end=" ")
 
    def Radix(self):
        """
 
        7 Radix Sort 基数排序
        :return:
        """
        geovindu = [170, 45, 75, 90, 802, 24, 2, 66]
        print("\n7 基数排序  Radix Sorted ")
        # Function Call
        ChapterOne.SortingAlgorithms.SortingAlgorithms.RadixSort(geovindu)
 
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Bucket(self):
        """
        8 Bucket Sort 桶排序
        :return:
        """
        # geovindu = [170, 45, 75, 90, 802, 24, 2, 66]
        geovindu = [0.897, 0.565, 0.656,
                    0.1234, 0.665, 0.3434]
        print("\n8 桶排序  Bucket Sorted ")
        # Function Call
        du = ChapterOne.SortingAlgorithms.SortingAlgorithms.BucketSort(geovindu)
        for i in range(len(du)):
            print(du[i], end=" ")
 
    def Heap(self):
        """
        9 Heap Sort 堆排序
        :return:
        """
        geovindu = [170, 45, 75, 90, 802, 24, 2, 66]
        print("\n9 堆排序  Heap Sorted ")
        # Function Call
        ChapterOne.SortingAlgorithms.SortingAlgorithms.HeapSort(geovindu)
 
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Shell(self):
        """
 
        10 Shell Sort 希尔排序
        :return:
        """
 
        geovindu = [170, 45, 75, 90, 802, 24, 2, 66]
        print("\n10 希尔排序  Shell Sorted ")
        # Function Call
        ChapterOne.SortingAlgorithms.SortingAlgorithms.ShellSort(geovindu)
 
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Linear(self):
        """
        11 Linear Search 线性搜索
        :return:
        """
        array = [2, 4, 8, 0, 1, 9]
        x = 8
        n = len(array)
        result = ChapterOne.SortingAlgorithms.SortingAlgorithms.LinearSearch(array, x)
        print("\n11 线性搜索  Linear Search ")
        if (result == -1):
            print("Element not found")
        else:
            print("Element found at index: ", result)
 
    def Binary(self):
        """
        12 Binary Search  二分查找
        :return:
        """
        array = [3, 4, 5, 6, 7, 8, 9]
        x = 4
 
        result = ChapterOne.SortingAlgorithms.SortingAlgorithms.BinarySearch(array, x, 0, len(array) - 1)
        print("\n12 二分查找  Binary Search ")
        if result != -1:
            print("Element is present at index " + str(result))
        else:
            print("Not found")
 
    def Bingo(self):
        """
        13 Bingo Sort宾果排序
        :return:
        """
        arr = [5, 4, 8, 5, 4, 8, 5, 4, 4, 4]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.BingoSort(arr, size=len(arr))
        print("\n13   Bingo Sorted ")
        for i in range(len(arr)):
            print(arr[i], end=" ")
 
    def Tim(self):
        """
        14  Tim Sort
        :return:
        """
        timearr = [-2, 7, 15, -14, 0, 15, 0,
                   7, -7, -4, -13, 5, 8, -14, 12]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.TimSort(timearr)
        print("\n14   Tim Sorted ")
        for i in range(len(timearr)):
            print(timearr[i], end=" ")
 
    def Comb(self):
        """
        15  Comb Sort
        :return:
        """
        geovindu = [8, 4, 1, 56, 3, -44, 23, -6, 28, 0]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.CombSort(geovindu)
        print("\n15   Comb Sorted ")
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Pigeonhole(self):
        """
        16  Pigeonhole Sort 鸽巢排序
        :return:
        """
        geovindu = [8, 3, 2, 7, 4, 6, 8]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.PigeonholeSort(geovindu)
        print("\n16  鸽巢排序 Pigeonhole Sorted ")
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Cycle(self):
        """
        17 Cycle Sort 循环排序
        :return:
        """
        geovindu = [8, 3, 2, 7, 4, 6, 8]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.CycleSort(geovindu)
        print("\n17  循环排序 Cycle Sorted ")
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Cocktail(self):
        """
        18 Cocktail Sort 鸡尾酒排序
        :return:
        """
        geovindu = [8, 3, 2, 7, 4, 6, 8]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.CocktailSort(geovindu)
        print("\n18  鸡尾酒排序 Cocktail Sorted ")
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Strand(self):
        """
 
        19 Strand Sort 经典排序
        :return:
        """
        geovindu = [8, 3, 2, 7, 4, 6, 8]
        ourdata = ChapterOne.SortingAlgorithms.SortingAlgorithms.StrandSort(geovindu)
        print("\n19 经典排序 Strand Sorted ")
        for i in range(len(ourdata)):
            print(ourdata[i], end=" ")
 
    def Bitonic(self):
        """
        20  Bitonic Sort 双调排序
        :return:
        """
        geovindu = [8, 3, 2, 7, 4, 6, 8]
        n = len(geovindu)
        up = 1
        ChapterOne.SortingAlgorithms.SortingAlgorithms.BitonicSort(geovindu, n, up)
        print("\n20 双调排序 Bitonic Sorted ")
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Pancake(self):
        """
        21 Pancake Sort 煎饼排序
        :return:
        """
        geovindu = [8, 3, 2, 7, 4, 6, 8]
        n = len(geovindu)
        ChapterOne.SortingAlgorithms.SortingAlgorithms.PancakeSort(geovindu, n)
        print("\n21 煎饼排序 Pancake Sorted ")
        for i in range(len(geovindu)):
            print(geovindu[i], end=" ")
 
    def Bogo(self):
        """
        22. Bogo Sort  BogoSort or Permutation Sort
        :return:
        """
        geovindu = [3, 2, 4, 1, 0, 5]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.BogoSort(geovindu)
        print("\n 22.置换排序 Bogo Sorted array :")
        for i in range(len(geovindu)):
            print("%d" % geovindu[i])
 
    def Gnome(self):
        """
        23 Gnome Sort 地精排序,也称侏儒排序
        :return:
        """
        geovindu = [34, 2, 10, -9]
        n = len(geovindu)
 
        arr = ChapterOne.SortingAlgorithms.SortingAlgorithms.GnomeSort(geovindu)
        print("23 地精排序 Sorted sequence after applying Gnome Sort :")
        for i in arr:
            print(i)
 
    def Sleep(self):
        """
        24.Sleep Sort 睡眠排序
        :return:
        """
        geovindu = [34, 23, 122, 9,100]
        print("\n24.Sleep Sort 睡眠排序 \n")
        ChapterOne.SortingAlgorithms.SortingAlgorithms.SleepSort(geovindu)
 
    def Stooge(self):
        """
        25 Stooge Sort 臭皮匠排序
        :return:
        """
        geovindu = [22, 4, 15, 3, 11]
        nsize = len(geovindu)
        print("\n25.Stooge Sort 臭皮匠排序 \n")
        ChapterOne.SortingAlgorithms.SortingAlgorithms.StoogeSort(geovindu, 0, nsize - 1)
 
        for i in range(0, nsize):
            print(geovindu[i], end=' ')
 
    def Tag(self):
        """
        26 Tag Sort (To get both sorted and original)
        :return:
        """
        n = 5
        persons = [ChapterOne.Person.Person(0, 233.5,"geovindu"), ChapterOne.Person.Person(1, 23,"geo"), ChapterOne.Person.Person(2, 13.98,"涂聚文"), ChapterOne.Person.Person(3, 143.2,"tujuwen"), ChapterOne.Person.Person(4, 3,"geovin")]
        tag = [i for i in range(n)]
 
        # Every Person object is tagged to an element in the tag array.
        print("\n26.Given Person and Tag")
        for i in range(n):
            print(str(persons[i]) + " : Tag: " + str(tag[i]))
 
        # Modifying tag array so that we can access persons in sorted order.
        ChapterOne.SortingAlgorithms.SortingAlgorithms.TagSort(persons, tag)
 
        print("\nNew Tag Array after getting sorted as per Person[]")
        for i in range(n):
            print(tag[i])
 
        # Accessing persons in sorted (by salary) way using modified tag array.
        for i in range(n):
            print(persons[tag[i]])
 
    def Tree(self):
        """
        27 Tree Sort
        :return:
        """
        print("\n27 Tree Sort")
        geovindu = [5, 4, 7, 2, 11]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.treedemo(geovindu)
 
 
 
    def Brick(self):
        """
        28.Brick Sort / Odd-Even Sort 砖排序算法(Brick Sort),也被称为奇偶排序(Odd-Even Sort)
        :return:
        """
        geovindu = [34, 2, 10, -9]
        ChapterOne.SortingAlgorithms.SortingAlgorithms.BrickSort(geovindu);
        print("\n 28. 砖排序算法 Brick Sort")
        for i in range(0, len(geovindu)):
            print(geovindu[i], end=' ')
 
    def MergeWay(self):
        """
        29. 3-way Merge Sort ·3路归并排序
        :return:
        """
        data = [45, -2, -45, 78, 30, -42, 10, 19, 73, 93]
        data = ChapterOne.SortingAlgorithms.SortingAlgorithms.MergeSort3Way(data)
        print("\n29.After 3 way merge sort: ", end="")
        for i in range(len(data)):
            print(f"{data[i]} ", end="")

  

调用:

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
# encoding: utf-8
# 版权所有 2023 ©涂聚文有限公司
# 许可信息查看:
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# Datetime  : 2023/9/26 11:03
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : main.py
# explain   : 学习
 
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
 
 
import BLL.SortExample
import BLL.ChaperExample
import BLL.AlgorithmExample
 
 
def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}'# Press Ctrl+F8 to toggle the breakpoint.
 
 
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm,涂聚文,你好!')
    #app=ChapterOne.ChaperI.ChapIApp();
 
    #BLL.ChaperExample.ChapterIExample.ChI()
    #BLL.ChaperExample.ChapterIExample.ChII()
    #BLL.ChaperExample.ChapterIExample.ChIII()
    #BLL.ChaperExample.ChapterIExample.ChGcd()
    al=BLL.AlgorithmExample.AlExample()
    al.Krusal()
    al.FoordFulkerson()
    al.Dijkstras()
    al.Prim()
    al.PrimTwo()
    al.Huffman()
 
    exm = BLL.SortExample.Example()
    exm.Bubble()
    exm.Select()
    exm.Insert()
    exm.Quick()
    exm.Merge()
    exm.Counting()
    exm.Radix()
    exm.Bucket()
    exm.Heap()
    exm.Shell()
    exm.Linear()
    exm.Binary()
    exm.Bingo()
    exm.Tim()
    exm.Comb()
    exm.Pigeonhole()
    exm.Cycle()
    exm.Cocktail()
    exm.Strand()
    exm.Bitonic()
    exm.Pancake()
    exm.Bogo()
    exm.Gnome()
    exm.Sleep()
    exm.Stooge()
    exm.Tag()
    exm.Tree()
    exm.Brick()
    exm.MergeWay()
 
 
 
 
# See PyCharm help at https://www.jetbrains.com/help/pycharm/

  

 

posted @   ®Geovin Du Dream Park™  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2022-09-27 CSharp: Chain of Responsibility Pattern
2022-09-27 Java: Command Pattern
2022-09-27 CSharp: Proxy Pattern
2017-09-27 sql server: left join 重复数据
2015-09-27 sql: table,view,function, procedure created MS_Description in sql server
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示