Python: Two Dimensional (2D) Array Bubble Sort
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# Datetime : 2024/4/28 10:37
# User : geovindu
# Product : PyCharm
# Project : EssentialAlgorithms
# File : example.py
# explain : 学习
#封装另作
table = [ ['1', 'Du', 'GeovinDu', '13824350518',92],
['2', 'Rose', 'Tom', '1882458888',38],
['3', 'Lin', 'bo', '18520000000',87],
['4', 'Ada', 'Jaing', '1899999999',87]]
# Bubble Sort冒泡排序法
columnindex=1 #改变列排序,考虑列的数据类型
#print(type(table[0][columnindex]),table[0][columnindex])
for i in range(0,len(table)-1):
# 考虑数据类型
#print(table[i][j],table[i+1][j],table[i],table[i+1])
if type(table[i][columnindex])==int:
if table[i][columnindex]<table[i+1][columnindex]:
temp = table[i]
table[i] = table[i+1]
table[i+1] = temp
if type(table[i][columnindex])==str:
if table[i][columnindex][0].lower()<table[i+1][columnindex][0].lower(): #第一个字母排序,以小写字母
temp = table[i]
table[i] = table[i+1]
table[i+1] = temp
print(table)
简单封装:
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# Datetime : 2024/4/28 10:37
# User : geovindu
# Product : PyCharm
# Project : EssentialAlgorithms
# File : example.py
# explain : 学习
def BubbleSort(table:list,columnindex:int)->list:
"""
:param table: Two Dimensional (2D) Array
:param columnindex: 需要排序的列的索引
:return:
"""
for i in range(0, len(table) - 1):
# 考虑数据类型
# print(table[i][j],table[i+1][j],table[i],table[i+1])
if type(table[i][columnindex]) == int:
if table[i][columnindex] < table[i + 1][columnindex]:
temp = table[i]
table[i] = table[i + 1]
table[i + 1] = temp
if type(table[i][columnindex]) == str:
if table[i][columnindex][0].lower() < table[i + 1][columnindex][0].lower(): # 第一个字母排序,以小写字母
temp = table[i]
table[i] = table[i + 1]
table[i + 1] = temp
return table
调用:
if __name__=="__main__":
"""
main import
"""
table = [['1', 'Du', 'GeovinDu', '13824350518', 92],
['2', 'Rose', 'Tom', '1882458888', 38],
['3', 'Lin', 'bo', '852000000', 87],
['4', 'Ada', 'Jaing', '18999999999', 87]]
BubbleSort(table,4)
print(table)
原文地址:https://blog.csdn.net/geovindu/article/details/142726506
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!