用 Python 编写一个针对数值数据集的排序算法?
programmingpythonserver side programming更新于 2025/3/18 19:56:17
Python 中的数值数据集适用于数值数据类型。整数排序算法,在 Python 中包含以下内容 -
- 冒泡排序
- 希尔排序
- 选择排序
Python 中的冒泡排序
冒泡排序是基于比较的排序。相邻元素进行比较和交换以形成正确的序列 -
示例
def bubblesort(myList): # Swap the elements to arrange in order for iter_num in range(len(myList)-1,0,-1): for idx in range(iter_num): if myList[idx]>myList[idx+1]: temp = myList[idx] myList[idx] = myList[idx+1] myList[idx+1] = temp # Unsorted List myList = [40, 23, 7, 49, 32, 98, 76, 48, 87] print("Unsorted List = ",myList) # Calling the function bubblesort(myList) print("Sorted List = ",myList)
输出
Unsorted List = [40, 23, 7, 49, 32, 98, 76, 48, 87] Sorted List = [7, 23, 32, 40, 48, 49, 76, 87, 98]
Python 中的 Shell 排序
对于 Shell 排序,定义一个函数并将列表和列表的长度作为参数。此列表按特定数量的元素排序,其中元素数量为最大值。此过程一直进行到元素数量具有最小值为止。
示例
def shell_sort(my_list, list_len): interval = list_len // 2 while interval > 0: for i in range(interval, list_len): temp = my_list[i] j = i while j >= interval and my_list[j - interval] > temp: my_list[j] = my_list[j - interval] j -= interval my_list[j] = temp interval //= 2 my_list = [40, 23, 7, 49, 32, 98, 76, 48, 87] list_len = len(my_list) print ("The list before sorting is :") print(my_list) shell_sort(my_list, list_len) print ("\nThe list after performing shell sorting is :") print(my_list)
输出
The list before sorting is : [40, 23, 7, 49, 32, 98, 48, 87] The list after performing shell sorting is : [7, 23, 32, 40, 48, 49, 87, 98]
Python 中的选择排序
在选择排序算法中,数组通过递归方式从未排序部分找到最小元素并将其插入开头来排序。在给定数组上执行选择排序时会形成两个子数组。
已排序的子数组
未排序的子数组。
以下是代码 −
示例
A = ['h','o','w','a','r','e','y','o','u'] for i in range(len(A)): min_= i for j in range(i+1, len(A)): if A[min_] > A[j]: min_ = j #swap A[i], A[min_] = A[min_], A[i] # main for i in range(len(A)): print(A[i])
输出
a e h o o r u w y
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

