首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python: Two Dimensional (2D) Array Bubble Sort

Python: Two Dimensional (2D) Array Bubble Sort

作者头像
geovindu
发布2026-06-18 20:43:47
发布2026-06-18 20:43:47
920
举报
代码语言:javascript
复制
# 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)

简单封装:

代码语言:javascript
复制
# 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

调用:

代码语言:javascript
复制
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)
代码语言:javascript
复制
# 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   : 学习

class Sort(object):
    """

    """
    
    @staticmethod
    def BubbleSort(table: list, columnindex=4) -> list:
        """
        :param table: Two Dimensional (2D) Array
        :param columnindex: 需要排序的列索引
        :return: tabe sorted
        """
        if type(table[0])==list:  #二维列表
            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():  # 第一个字母排序,以小写字母 以小写字母,以字母的ASCII的值比較
                        temp = table[i]
                        table[i] = table[i + 1]
                        table[i + 1] = temp
        else:
            # 一维列表
            for i in range(len(table)):
                for j in range(0, len(table) - i - 1):
                    if type(table[i]) == int:
                        if table[j] > table[j + 1]:
                            temp = table[j]
                            table[j] = table[j + 1]
                            table[j + 1] = temp
                    
                    if type(table[i]) == str:
                         if table[j][0] > table[j + 1][0]:
                            temp = table[j]
                            table[j] = table[j + 1]
                            table[j + 1] = temp

        return table
    

if __name__=="__main__":
    
    table = [ ['1', 'Du', 'GeovinDu', '13824350518',92],
                 ['2', 'Rose', 'Tom', '1882458888',38],
                 ['3', 'Lin', 'bo', '852000000',87],
                 ['4', 'Ada', 'Jaing', '18999999999',87]]

    print(type(table))
    print(type(table[0]))
    if type(table[0])==list:
        print('list')
    else:
        print('not list')
        

    Sort.BubbleSort(table,4)
    print(table)
    
        
        
    
    row=[1, 5, 7, 0,92]
    print(type(row))
    print(type(row[0]))
    if type(row[0])!=list:
        print('not list')
    else:
        print('is list')
        
    Sort.BubbleSort(row)
    print(row)
    
    row=['1', 'Du', 'GeovinDu', '13824350518','92']
    Sort.BubbleSort(row)
    
    
    print(row)
代码语言:javascript
复制
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:
# 描述: 
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# Datetime  : 2024/09/28 20:28
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : example.py


class Pepole(object):
    """

    """
    def __init__(self):
        """

        """
        self._id=None 
        self._realname=None
        self._tel=None
        self._age=None
        
    @property
    def Id(self):
        """
        """
        return self._id
    
    @Id.setter
    def Id(self,ids):
        """
        """
        self._id=ids
        
    @property
    def RealName(self):
        """
        
        :return: 
        """
        return self._realname
    
    @RealName.setter
    def RealName(self,realname):
        """
        
        :param realname: 
        :return: 
        """
        self._realname=realname
        
        
    @property
    def Tel(self):
        """
        
        :return: 
        """
        return self._tel
    
    @Tel.setter
    def Tel(self,tel):
        """
        
        :param tel: 
        :return: 
        """
        self._tel=tel
        
    @property
    def Age(self):
        """
        
        :return: 
        """
        return self._age
    
    @Age.setter
    def Age(self,age):
        """
        
        :param age: 
        :return: 
        """
        self._age=age
        
        
        
table=[]
p=Pepole()
p.Id='1'
p.RealName="geovindu"
p.Tel="13824350518"
p.Age=28
table.append(p)
p=Pepole()
p.Id='2'
p.RealName="sibo"
p.Tel="13324350518"
p.Age=18
table.append(p)
p=Pepole()
p.Id='3'
p.RealName="zaoti"
p.Tel="13624350518"
p.Age=22
table.append(p)
p=Pepole()
p.Id='4'
p.RealName="jiang"
p.Tel="13524350518"
p.Age=12
table.append(p)
p=Pepole()
p.Id='5'
p.RealName="xiaobiao"
p.Tel="13224350518"
p.Age=20
table.append(p)

# 1
tablesore=sorted(table, key=lambda Pepole: Pepole.Age, reverse=True) 
for info in tablesore:
    print(info.Id,info.RealName,info.Tel,info.Age)
    
# 2    
table.sort(key=lambda Pepole: (Pepole.Age,Pepole.Id), reverse=True)
for info in table:
    print(info.Id,info.RealName,info.Tel,info.Age)    
    
# from https://docs.python.org/3/howto/descriptor.html
# from https://docs.python.org/3/library/functions.html
# from https://docs.python.org/3/howto/sorting.html

]

代码语言:javascript
复制
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:
# 描述: 
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# Datetime  : 2024/09/28 20:28
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : example.py

from enum import Enum


class PepoleCollation(Enum):
    """
    選擇字段排序
    """
    Id=1,
    """

    """
    RealName=2,
    """

    """
    Tel=3,
    """

    """
    Age=4
    """

    """
    

class Pepole(object):
    """

    """
    def __init__(self):
        """

        """
        self._id=None 
        self._realname=None
        self._tel=None
        self._age=None
        
    @property
    def Id(self):
        """
        """
        return self._id
    
    @Id.setter
    def Id(self,ids):
        """
        """
        self._id=ids
        
    @property
    def RealName(self):
        """
        
        :return: 
        """
        return self._realname
    
    @RealName.setter
    def RealName(self,realname):
        """
        
        :param realname: 
        :return: 
        """
        self._realname=realname
        
        
    @property
    def Tel(self):
        """
        
        :return: 
        """
        return self._tel
    
    @Tel.setter
    def Tel(self,tel):
        """
        
        :param tel: 
        :return: 
        """
        self._tel=tel
        
    @property
    def Age(self):
        """
        
        :return: 
        """
        return self._age
    
    @Age.setter
    def Age(self,age):
        """
        
        :param age: 
        :return: 
        """
        self._age=age
        
     
     
def Sort(table:list,check: PepoleCollation,isDesc=True)->list:
    """
    object Pepole list
    :param  table
    :param  check
    :param  isDesc 
    """
    #check=PepoleCollationField.Age
    if PepoleCollation.Age==check:
        print("age desc",PepoleCollation.Age)
        table.sort(key=lambda Pepole: (Pepole.Age,Pepole.Id), reverse=isDesc)
    elif PepoleCollation.Id==check:
        table.sort(key=lambda Pepole: (Pepole.Id), reverse=isDesc)
    elif PepoleCollation.RealName==check:
        table.sort(key=lambda Pepole: (Pepole.RealName), reverse=isDesc)
    elif PepoleCollation.Tel==check:
        table.sort(key=lambda Pepole: (Pepole.Tel), reverse=isDesc)
    else:
        table.sort(key=lambda Pepole: (Pepole.Id), reverse=isDesc)

    for info in table:
        print(info.Id,info.RealName,info.Tel,info.Age)
        
     
        
table=[]
p=Pepole()
p.Id='1'
p.RealName="geovindu"
p.Tel="13824350518"
p.Age=28
table.append(p)
p=Pepole()
p.Id='2'
p.RealName="sibo"
p.Tel="13324350518"
p.Age=18
table.append(p)
p=Pepole()
p.Id='3'
p.RealName="zaoti"
p.Tel="13624350518"
p.Age=22
table.append(p)
p=Pepole()
p.Id='4'
p.RealName="jiang"
p.Tel="13524350518"
p.Age=12
table.append(p)
p=Pepole()
p.Id='5'
p.RealName="xiaobiao"
p.Tel="13224350518"
p.Age=20
table.append(p)

# 1
tablesore=sorted(table, key=lambda Pepole: Pepole.Age, reverse=True) 
for info in tablesore:
    print(info.Id,info.RealName,info.Tel,info.Age)
print('***************')  
# 2
Sort(table, PepoleCollation.Age,False)
Sort(table, PepoleCollation.Age)
    
# from https://docs.python.org/3/howto/descriptor.html
# from https://docs.python.org/3/library/functions.html
# from https://docs.python.org/3/howto/sorting.html
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-10-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档