python a primary (302) 7 list (ii) bubble sort

First, review:

1, how to create an empty list, how to create a list of data

2, the list may contain content

3, and acquires the element list element from a modified method of

4, the list of fragment

5, adding elements and remove elements

6, selection sort algorithm:

A bunch of data, find the smallest each into a new array, then the number of the original array removed until the original array is empty

 

Second, the bubble sort

A bunch of data, from left to right, each comparison of two numbers adjacent to the former than the latter a large, exchange position, and then continue the comparison, has been compared to the maximum of the bottom of the queue. Then traverse the array again, this last one has been lined up, so just than the penultimate, and so on

Data: arr = [9, 7, 8, 4]:

The first big cycle:

1 [7, 9, 8, 4]

2 [7, 8, 9, 4]

3 [7, 8, 4, 9]

The second big cycle:

1 [7, 8, 4, 9]

2 [7, 4, 8, 9]

The third big cycle:

[4, 7, 8, 9]

 

Procedures are as follows:

def maopao(arr):
    """
    Bubble Sort
    """
    # arr = [9, 7, 8, 4]
    n = len(arr)
    for i in range(n-1):
        for j in range(n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr


my_arr = [9, 7, 8, 4]
print(my_arr)
maopao(my_arr)
print(my_arr)

 

Third, homework

The students in the class with a bubble sort of math sorted (in descending order)

95, 98, 97, 100, 80, 93, 99

Guess you like

Origin www.cnblogs.com/luhouxiang/p/12078774.html