python: Algorithms
# 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)
# 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
# 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) + "}"
# 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 i # 找到了
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
# 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="")
调用:
# 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/
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
浙公网安备 33010602011771号