Python 冒泡排序程序

编写一个 Python 程序,使用 for 循环、while 循环和函数以及实际示例,通过冒泡排序对列表项进行排序。

Python 冒泡排序程序(For 循环)

此程序允许用户输入列表大小。接下来,我们使用 For 循环将元素插入其中。之后,我们使用冒泡排序算法来组织列表项。

提示:请参考 列表 文章,了解 Python 中所有关于列表的内容。

a = []
number = int(input("Please Enter the Total Elements : "))
for i in range(number):
    value = int(input("Please enter the %d Item : " %i))
    a.append(value)

for i in range(number -1):
    for j in range(number - i - 1):
        if(a[j] > a[j + 1]):
             temp = a[j]
             a[j] = a[j + 1]
             a[j + 1] = temp

print("The Result in Ascending Order : ", a)
program for Bubble Sort

在此 Python 程序中,我们使用嵌套的 For 循环 来遍历给定列表中的每个元素。接下来,我们在程序循环中使用 If 语句,以冒泡排序的方式按升序对项目进行排序。

第一个 For 循环 – 第一次迭代: for o in range (3)
条件为 True。因此,它进入第二个 for 循环。

第二个 For 循环 – 第一次迭代: for o in range(4 – 0 – 1)。For 循环中的条件为 True。因此,它进入 If 语句

if(a[0] > a[1]) => if(10 > -4) – 这意味着条件为 True。
temp = 10
a[j] = a[j + 1] => a[0] = a[1] => a[0] = -4
a[j + 1] = temp => a[1] = 10

现在列表为: -4 10 10 5。

第二个 For 循环 – 第二次迭代: for 1 in range(4 – 0 – 1) – True
if(10 > 10) – 这意味着条件为 False。对剩余的迭代执行相同的操作。

Python 冒泡排序程序(While 循环)

这与上面的程序相同。但是,我们用 While 循环 替换了 for 循环,以使用冒泡排序对列表元素进行排序。

a = []
number = int(input("Please Enter the Total Number of Elements : "))
for i in range(number):
    value = int(input("Please enter the %d Element : " %i))
    a.append(value)

i = 0
while(i < number -1):
    j = 0
    while(j < number - i - 1):
        if(a[j] > a[j + 1]):
             temp = a[j]
             a[j] = a[j + 1]
             a[j + 1] = temp
        j = j + 1
    i = i + 1

print("The List in Ascending Order : ", a)
Please Enter the Total Number of Elements : 5
Please enter the 0 Element : 5
Please enter the 1 Element : -3
Please enter the 2 Element : 10
Please enter the 3 Element : 5
Please enter the 4 Element : 7
The List in Ascending Order :  [-3, 5, 5, 7, 10]

冒泡排序程序(函数)

此冒泡排序程序与第一个示例相同。但是,我们将逻辑分离出来,使用 函数 来对列表元素进行排序。

def bubFunc(a, val):
    for i in range(val -1):
        for j in range(val - i - 1):
            if(a[j] > a[j + 1]):
                 temp = a[j]
                 a[j] = a[j + 1]
                 a[j + 1] = temp

a = []
val = int(input("Please Enter the Total Elements : "))
for i in range(val):
    value = int(input("Please enter the %d Element : " %i))
    a.append(value)

bubFunc(a, val)
print("The List in Ascending Order : ", a)
Please Enter the Total Elements : 4
Please enter the 0 Element : 2
Please enter the 1 Element : 1
Please enter the 2 Element : -1
Please enter the 3 Element : 0
The List in Ascending Order :  [-1, 0, 1, 2]