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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值