• python: Sorting Algorithms


    1. # encoding: utf-8
    2. # 版权所有 2023 涂聚文有限公司
    3. # 许可信息查看:Python Sorting Algorithms
    4. # 描述: * https://www.programiz.com/dsa/counting-sort
    5. # * https://www.geeksforgeeks.org/sorting-algorithms/
    6. # Author : geovindu,Geovin Du 涂聚文.
    7. # IDE : PyCharm 2023.1 python 311
    8. # Datetime : 2023/9/21 21:55
    9. # User : geovindu
    10. # Product : PyCharm
    11. # Project : EssentialAlgorithms
    12. # File : SortingAlgorithms.py
    13. # explain : 学习
    14. import tkinter as tk
    15. from tkinter import ttk
    16. import itertools
    17. import math
    18. import sys
    19. import os
    20. from typing import List
    21. class SortingAlgorithms(object):
    22. """
    23. 排序算法
    24. """
    25. def BubbleSort(array:list):
    26. """
    27. 1。Bubble Sort冒泡排序法
    28. :param array int数组
    29. :return:
    30. """
    31. # loop to access each array element
    32. for i in range(len(array)):
    33. # loop to compare array elements
    34. for j in range(0, len(array) - i - 1):
    35. # compare two adjacent elements
    36. # change > to < to sort in descending order
    37. if array[j] > array[j + 1]:
    38. # swapping elements if elements
    39. # are not in the intended order
    40. temp = array[j]
    41. array[j] = array[j + 1]
    42. array[j + 1] = temp
    43. def BubbleSort2(array:list):
    44. """
    45. 1。Bubble Sort冒泡排序法
    46. :param array int数组
    47. :return:
    48. """
    49. # loop through each element of array
    50. for i in range(len(array)):
    51. # keep track of swapping
    52. swapped = False
    53. # loop to compare array elements
    54. for j in range(0, len(array) - i - 1):
    55. # compare two adjacent elements
    56. # change > to < to sort in descending order
    57. if array[j] > array[j + 1]:
    58. # swapping occurs if elements
    59. # are not in the intended order
    60. temp = array[j]
    61. array[j] = array[j + 1]
    62. array[j + 1] = temp
    63. swapped = True
    64. # no swapping means the array is already sorted
    65. # so no need for further comparison
    66. if not swapped:
    67. break
    68. def SelectionSort(array:list):
    69. """
    70. 2 python Program for Selection Sort 选择排序
    71. :param array int数组
    72. :return:
    73. """
    74. for i in range(len(array)):
    75. # Find the minimum element in remaining
    76. # unsorted array
    77. min_idx = i
    78. for j in range(i+1, len(array)):
    79. if array[min_idx] > array[j]:
    80. min_idx = j
    81. # Swap the found minimum element with
    82. # the first element
    83. array[i], array[min_idx] = array[min_idx], array[i]
    84. def InsertionSort(array:list):
    85. """
    86. 3 Insertion Sort插入排序
    87. :param array int数组
    88. :return:
    89. """
    90. # Traverse through 1 to len(arr)
    91. for i in range(1, len(array)):
    92. key = array[i]
    93. # Move elements of arr[0..i-1], that are
    94. # greater than key, to one position ahead
    95. # of their current position
    96. j = i - 1
    97. while j >= 0 and key < array[j]:
    98. array[j + 1] = array[j]
    99. j -= 1
    100. array[j + 1] = key
    101. def Partition(array, low, high):
    102. """
    103. :param array int数组
    104. :param low:
    105. :param high:
    106. :return:
    107. """
    108. # Choose the rightmost element as pivot
    109. pivot = array[high]
    110. # Pointer for greater element
    111. i = low - 1
    112. # Traverse through all elements
    113. # compare each element with pivot
    114. for j in range(low, high):
    115. if array[j] <= pivot:
    116. # If element smaller than pivot is found
    117. # swap it with the greater element pointed by i
    118. i = i + 1
    119. # Swapping element at i with element at j
    120. (array[i], array[j]) = (array[j], array[i])
    121. # Swap the pivot element with
    122. # the greater element specified by i
    123. (array[i + 1], array[high]) = (array[high], array[i + 1])
    124. # Return the position from where partition is done
    125. return i + 1
    126. def QuickSort(array, low, high):
    127. """
    128. 4 Quick Sort 快速排序
    129. :param array int数组
    130. :param low:
    131. :param high:
    132. :return:
    133. """
    134. if low < high:
    135. # Find pivot element such that
    136. # element smaller than pivot are on the left
    137. # element greater than pivot are on the right
    138. pi = SortingAlgorithms.Partition(array, low, high)
    139. # Recursive call on the left of pivot
    140. SortingAlgorithms.QuickSort(array, low, pi - 1)
    141. # Recursive call on the right of pivot
    142. SortingAlgorithms.QuickSort(array, pi + 1, high)
    143. def MergeSort(array:list):
    144. """
    145. 5 Merge Sort 合并/归并排序
    146. :param array int数组
    147. :return:
    148. """
    149. if len(array) > 1:
    150. # Finding the mid of the array
    151. mid = len(array) // 2
    152. # Dividing the array elements
    153. L = array[:mid]
    154. # Into 2 halves
    155. R = array[mid:]
    156. # Sorting the first half
    157. SortingAlgorithms.MergeSort(L)
    158. # Sorting the second half
    159. SortingAlgorithms.MergeSort(R)
    160. i = j = k = 0
    161. # Copy data to temp arrays L[] and R[]
    162. while i < len(L) and j < len(R):
    163. if L[i] <= R[j]:
    164. array[k] = L[i]
    165. i += 1
    166. else:
    167. array[k] = R[j]
    168. j += 1
    169. k += 1
    170. # Checking if any element was left
    171. while i < len(L):
    172. array[k] = L[i]
    173. i += 1
    174. k += 1
    175. while j < len(R):
    176. array[k] = R[j]
    177. j += 1
    178. k += 1
    179. def CountingSort(array:list,hight:int):
    180. """
    181. 6 Counting Sort 计数排序
    182. :param array int数组
    183. :param hight 最大的整数 如100,数组中必须小数此数的整数
    184. :return:
    185. """
    186. size = len(array)
    187. output = [0] * size
    188. # Initialize count array
    189. dcount = [0] * hight
    190. # Store the count of each elements in count array
    191. print(size)
    192. for i in range(0, size):
    193. dcount[array[i]] += 1
    194. # Store the cummulative count 最大的数
    195. for i in range(1, hight):
    196. dcount[i] += dcount[i - 1]
    197. # Find the index of each element of the original array in count array
    198. # place the elements in output array
    199. i = size - 1
    200. while i >= 0:
    201. output[dcount[array[i]] - 1] = array[i]
    202. dcount[array[i]] -= 1
    203. i -= 1
    204. # Copy the sorted elements into original array
    205. for i in range(0, size):
    206. array[i] = output[i]
    207. def CountingSortTo(array: List[int]):
    208. """
    209. 6 Counting Sort 计数排序
    210. :param
    211. :return:
    212. """
    213. max = min = 0
    214. for i in array:
    215. if i < min:
    216. min = i
    217. if i > max:
    218. max = i
    219. count = [0] * (max - min + 1)
    220. for j in range(max - min + 1):
    221. count[j] = 0
    222. for index in array:
    223. count[index - min] += 1
    224. index = 0
    225. for a in range(max - min + 1):
    226. for c in range(count[a]):
    227. array[index] = a + min
    228. index += 1
    229. def countingSort(array, exp1):
    230. """
    231. :param array
    232. :param exp1:
    233. :return:
    234. """
    235. n = len(array)
    236. # The output array elements that will have sorted arr
    237. output = [0] * (n)
    238. # initialize count array as 0
    239. count = [0] * (10)
    240. # Store count of occurrences in count[]
    241. for i in range(0, n):
    242. index = array[i] // exp1
    243. count[index % 10] += 1
    244. # Change count[i] so that count[i] now contains actual
    245. # position of this digit in output array
    246. for i in range(1, 10):
    247. count[i] += count[i - 1]
    248. # Build the output array
    249. i = n - 1
    250. while i >= 0:
    251. index = array[i] // exp1
    252. output[count[index % 10] - 1] = array[i]
    253. count[index % 10] -= 1
    254. i -= 1
    255. # Copying the output array to arr[],
    256. # so that arr now contains sorted numbers
    257. i = 0
    258. for i in range(0, len(array)):
    259. array[i] = output[i]
    260. def RadixSort(array:list):
    261. """
    262. 7 Radix Sort 基数排序
    263. :param array
    264. :return:
    265. """
    266. # Find the maximum number to know number of digits
    267. max1 = max(array)
    268. # Do counting sort for every digit. Note that instead
    269. # of passing digit number, exp is passed. exp is 10^i
    270. # where i is current digit number
    271. exp = 1
    272. while max1 / exp >= 1:
    273. SortingAlgorithms.countingSort(array, exp)
    274. exp *= 10
    275. def insertionSort(array:list):
    276. """
    277. :return:
    278. """
    279. for i in range(1, len(array)):
    280. up = array[i]
    281. j = i - 1
    282. while j >= 0 and array[j] > up:
    283. array[j + 1] = array[j]
    284. j -= 1
    285. array[j + 1] = up
    286. return array
    287. def BucketSort(array):
    288. """
    289. 8 Bucket Sort 桶排序
    290. :param array
    291. :return:
    292. """
    293. arr = []
    294. slot_num = 10 # 10 means 10 slots, each
    295. # slot's size is 0.1
    296. for i in range(slot_num):
    297. arr.append([])
    298. # Put array elements in different buckets
    299. for j in array:
    300. index_b = int(slot_num * j)
    301. arr[index_b].append(j)
    302. # Sort individual buckets
    303. for i in range(slot_num):
    304. arr[i] = SortingAlgorithms.insertionSort(arr[i])
    305. # concatenate the result
    306. k = 0
    307. for i in range(slot_num):
    308. for j in range(len(arr[i])):
    309. array[k] = arr[i][j]
    310. k += 1
    311. return array
    312. # Bucket Sort in Python
    313. def BucketSortTo(array:list):
    314. """
    315. 8 Bucket Sort 桶排序
    316. :param array
    317. :return:
    318. """
    319. bucket = []
    320. # Create empty buckets
    321. for i in range(len(array)):
    322. bucket.append([])
    323. # Insert elements into their respective buckets
    324. for j in array:
    325. index_b = int(10 * j)
    326. bucket[index_b].append(j)
    327. # Sort the elements of each bucket
    328. for i in range(len(array)):
    329. bucket[i] = sorted(bucket[i])
    330. # Get the sorted elements
    331. k = 0
    332. for i in range(len(array)):
    333. for j in range(len(bucket[i])):
    334. array[k] = bucket[i][j]
    335. k += 1
    336. return array
    337. def heapify(array:list, Nsize:int, index:int):
    338. """
    339. :param array 数组
    340. :param Nsize: 数组长度
    341. :param index: 索引号
    342. :return:
    343. """
    344. largest = index # Initialize largest as root
    345. l = 2 * index + 1 # left = 2*i + 1
    346. r = 2 * index + 2 # right = 2*i + 2
    347. # See if left child of root exists and is
    348. # greater than root
    349. if l < Nsize and array[largest] < array[l]:
    350. largest = l
    351. # See if right child of root exists and is
    352. # greater than root
    353. if r < Nsize and array[largest] < array[r]:
    354. largest = r
    355. # Change root, if needed
    356. if largest != index:
    357. array[index], array[largest] = array[largest], array[index] # swap
    358. # Heapify the root.
    359. SortingAlgorithms.heapify(array, Nsize, largest)
    360. # The main function to sort an array of given size
    361. def HeapSort(array:list):
    362. """
    363. 9 Heap Sort 堆排序
    364. :param array
    365. :return:
    366. """
    367. Nsize = len(array)
    368. # Build a maxheap.
    369. for i in range(Nsize // 2 - 1, -1, -1):
    370. SortingAlgorithms.heapify(array, Nsize, i)
    371. # One by one extract elements
    372. for i in range(Nsize - 1, 0, -1):
    373. array[i], array[0] = array[0], array[i] # swap
    374. SortingAlgorithms.heapify(array, i, 0)
    375. def ShellSort(array:list):
    376. """
    377. 10 Shell Sort 希尔排序
    378. :param array 数组
    379. :return:
    380. """
    381. # code here
    382. nszie=len(array)
    383. gap = nszie // 2
    384. while gap > 0:
    385. j = gap
    386. # Check the array in from left to right
    387. # Till the last possible index of j
    388. while j < nszie:
    389. i = j - gap # This will keep help in maintain gap value
    390. while i >= 0:
    391. # If value on right side is already greater than left side value
    392. # We don't do swap else we swap
    393. if array[i + gap] > array[i]:
    394. break
    395. else:
    396. array[i + gap], array[i] = array[i], array[i + gap]
    397. i = i - gap # To check left side also
    398. # If the element present is greater than current element
    399. j += 1
    400. gap = gap // 2
    401. def LinearSearch(array:list,fint:int):
    402. """
    403. 11 Linear Search线性搜索
    404. :param array 整数数组
    405. :param fint 要查找的数字
    406. :return:
    407. """
    408. nsize=len(array)
    409. # Going through array sequencially
    410. for i in range(0, nsize):
    411. if (array[i] == fint):
    412. return i #找到了
    413. return -1 #未找到
    414. def BinarySearch(array:list, x, low, high):
    415. """
    416. 12 Binary Search 二分查找
    417. :param x:
    418. :param low:
    419. :param high:
    420. :return:
    421. """
    422. if high >= low:
    423. mid = low + (high - low) // 2
    424. # If found at mid, then return it
    425. if array[mid] == x:
    426. return mid
    427. # Search the left half
    428. elif array[mid] > x:
    429. return SortingAlgorithms.BinarySearch(array, x, low, mid - 1)
    430. # Search the right half
    431. else:
    432. return SortingAlgorithms.BinarySearch(array, x, mid + 1, high)
    433. else:
    434. return -1
    435. def BingoSort(array, size):
    436. """
    437. :param array
    438. :param size:
    439. :return:
    440. """
    441. # Finding the smallest element From the Array
    442. bingo = min(array)
    443. # Finding the largest element from the Array
    444. largest = max(array)
    445. nextBingo = largest
    446. nextPos = 0
    447. while bingo < nextBingo:
    448. # Will keep the track of the element position to
    449. # shifted to their correct position
    450. startPos = nextPos
    451. for i in range(startPos, size):
    452. if array[i] == bingo:
    453. array[i], array[nextPos] = array[nextPos], array[i]
    454. nextPos += 1
    455. # Here we are finding the next Bingo Element
    456. # for the next pass
    457. elif array[i] < nextBingo:
    458. nextBingo = array[i]
    459. bingo = nextBingo
    460. nextBingo = largest
    1. # encoding: utf-8
    2. # 版权所有 2023 涂聚文有限公司
    3. # 许可信息查看:
    4. # 描述:
    5. # Author : geovindu,Geovin Du 涂聚文.
    6. # IDE : PyCharm 2023.1 python 311
    7. # Datetime : 2023/9/21 22:00
    8. # User : geovindu
    9. # Product : PyCharm
    10. # Project : EssentialAlgorithms
    11. # File : SortingExample.py
    12. # explain : 学习
    13. import ChapterOne.SortingAlgorithms
    14. class Example(object):
    15. """"
    16. 实例
    17. """
    18. def Bubble(self):
    19. """
    20. 1。Bubble Sort冒泡排序法
    21. :return:
    22. """
    23. data = [-2, 45, 0, 11, -9]
    24. ChapterOne.SortingAlgorithms.SortingAlgorithms.BubbleSort(data)
    25. print('\n1 冒泡排序法 Bubble Sorted Array in Ascending Order:')
    26. for i in range(len(data)):
    27. print("%d" % data[i], end=" ")
    28. def Select(self):
    29. """
    30. 2 Selection Sort 选择排序
    31. :return:
    32. """
    33. geovindu = [64, 25, 12, 22, 11]
    34. ChapterOne.SortingAlgorithms.SortingAlgorithms.SelectionSort(geovindu)
    35. print("\n2 选择排序Selection Sorted ")
    36. for i in range(len(geovindu)):
    37. print("%d" % geovindu[i], end=" ")
    38. def Insert(self):
    39. """
    40. 3 Insertion Sort插入排序
    41. :return:
    42. """
    43. arr = [12, 11, 13, 5, 6]
    44. ChapterOne.SortingAlgorithms.SortingAlgorithms.InsertionSort(arr)
    45. print("\n3 插入排序 Insertion Sorted ")
    46. for i in range(len(arr)):
    47. print("% d" % arr[i], end=" ")
    48. def Quick(self):
    49. """
    50. 4 Quick Sort 快速排序
    51. :return:
    52. """
    53. array = [10, 7, 8, 9, 1, 5]
    54. N = len(array)
    55. # Function call
    56. ChapterOne.SortingAlgorithms.SortingAlgorithms.QuickSort(array, 0, N - 1)
    57. print("\n4 快速排序 Quick Sorted ")
    58. for x in array:
    59. print(x, end=" ")
    60. def Merge(self):
    61. """
    62. 5 Merge Sort 合并/归并排序
    63. :return:
    64. """
    65. geovindu = [12, 11, 99, 13, 5, 6, 7,88,100]
    66. ChapterOne.SortingAlgorithms.SortingAlgorithms.MergeSort(geovindu)
    67. print("\n5 合并/归并排序 Merge Sorted ")
    68. for x in geovindu:
    69. print(x, end=" ")
    70. def Counting(self):
    71. """
    72. 6 Counting Sort 计数排序
    73. :return:
    74. """
    75. geovindu = [17, 56, 71, 38, 61, 62, 48, 28, 57, 42]
    76. ChapterOne.SortingAlgorithms.SortingAlgorithms.CountingSortTo(geovindu)
    77. print("\n6 计数排序 Counting Sorted ")
    78. print(geovindu)
    79. for i in range(0,len(geovindu)):
    80. print("% d" % geovindu[i], end=" ")
    81. geovindu = [4, 55, 22, 98, 9, 43, 11]
    82. ChapterOne.SortingAlgorithms.SortingAlgorithms.CountingSort(geovindu, 100)
    83. print("\n6 计数排序 Counting Sorted ")
    84. for x in geovindu:
    85. print(x, end=" ")
    86. def Radix(self):
    87. """
    88. 7 Radix Sort 基数排序
    89. :return:
    90. """
    91. geovindu = [170, 45, 75, 90, 802, 24, 2, 66]
    92. print("\n7 基数排序 Radix Sorted ")
    93. # Function Call
    94. ChapterOne.SortingAlgorithms.SortingAlgorithms.RadixSort(geovindu)
    95. for i in range(len(geovindu)):
    96. print(geovindu[i], end=" ")
    97. def Bucket(self):
    98. """
    99. 8 Bucket Sort 桶排序
    100. :return:
    101. """
    102. #geovindu = [170, 45, 75, 90, 802, 24, 2, 66]
    103. geovindu = [0.897, 0.565, 0.656,
    104. 0.1234, 0.665, 0.3434]
    105. print("\n8 桶排序 Bucket Sorted ")
    106. # Function Call
    107. du=ChapterOne.SortingAlgorithms.SortingAlgorithms.BucketSort(geovindu)
    108. for i in range(len(du)):
    109. print(du[i], end=" ")
    110. def Heap(self):
    111. """
    112. 9 Heap Sort 堆排序
    113. :return:
    114. """
    115. geovindu = [170, 45, 75, 90, 802, 24, 2, 66]
    116. print("\n9 堆排序 Heap Sorted ")
    117. # Function Call
    118. ChapterOne.SortingAlgorithms.SortingAlgorithms.HeapSort(geovindu)
    119. for i in range(len(geovindu)):
    120. print(geovindu[i], end=" ")
    121. def Shell(self):
    122. """
    123. 10 Shell Sort 希尔排序
    124. :return:
    125. """
    126. geovindu = [170, 45, 75, 90, 802, 24, 2, 66]
    127. print("\n10 希尔排序 Shell Sorted ")
    128. # Function Call
    129. ChapterOne.SortingAlgorithms.SortingAlgorithms.ShellSort(geovindu)
    130. for i in range(len(geovindu)):
    131. print(geovindu[i], end=" ")
    132. def Linear(self):
    133. """
    134. 11 Linear Search 线性搜索
    135. :return:
    136. """
    137. array = [2, 4, 8,0, 1, 9]
    138. x = 8
    139. n = len(array)
    140. result = ChapterOne.SortingAlgorithms.SortingAlgorithms.LinearSearch(array,x)
    141. print("\n11 线性搜索 Linear Search ")
    142. if (result == -1):
    143. print("Element not found")
    144. else:
    145. print("Element found at index: ", result)
    146. def Binary(self):
    147. """
    148. 12 Binary Search 二分查找
    149. :return:
    150. """
    151. array = [3, 4, 5, 6, 7, 8, 9]
    152. x = 4
    153. result = ChapterOne.SortingAlgorithms.SortingAlgorithms.BinarySearch(array, x, 0, len(array) - 1)
    154. print("\n12 二分查找 Binary Search ")
    155. if result != -1:
    156. print("Element is present at index " + str(result))
    157. else:
    158. print("Not found")
    159. def Bingo(self):
    160. """
    161. 13 Bingo Sort
    162. :return:
    163. """
    164. arr = [5, 4, 8, 5, 4, 8, 5, 4, 4, 4]
    165. ChapterOne.SortingAlgorithms.SortingAlgorithms.BingoSort(arr, size=len(arr))
    166. print("\n13 Bingo Sorted ")
    167. for i in range(len(arr)):
    168. print(arr[i], end=" ")

    调用:

    1. exm=BLL.SortingExample.Example()
    2. exm.Bubble()
    3. exm.Select()
    4. exm.Insert()
    5. exm.Quick()
    6. exm.Merge()
    7. exm.Counting()
    8. exm.Radix()
    9. exm.Bucket()
    10. exm.Heap()
    11. exm.Shell()
    12. exm.Linear()
    13. exm.Binary()
    14. exm.Bingo()

  • 相关阅读:
    超级实用的程序员接单平台,看完少走几年弯路,强推第一个!
    黑马瑞吉外卖之菜品的分页查询展示(难点)
    Scrapy使用GitHub上的ProxyPool代理池
    C++primeplusp(p356-386)
    学用 DevChat 的 VSCode 插件,体验AI智能编程工具 (一)
    华为机试真题 C++ 实现【用连续自然数之和来表达整数】
    Pygame 精准检测图像碰撞
    win11一直弹出用户账户控制怎么解决
    程序波的躺平之道:【1】遁入此门
    Linux ALSA驱动之Platform源码分析(wm8350.c)
  • 原文地址:https://blog.csdn.net/geovindu/article/details/133222137