Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Implementing Bubble Sort in Python

Implementing Bubble Sort in Python

Document Object Reference Manual Python3 Examples

Bubble sort is a simple sorting algorithm that repeatedly traverses the list to be sorted, comparing adjacent elements and swapping them until the whole list is sorted. The algorithm is named after the way smaller elements slowly "float" to the top of the sequence through swapping.

The code:

Example

def

bubble_sort

(

arr

)

:

    n

=

len

(

arr

)

   

for

i

in

range

(

n

)

:

       

for

j

in

range

(

0

,

n-i-

1

)

:

           

if

arr

[

j

]

arr

[

j+

1

]

:

                arr

[

j

]

,

arr

[

j+

1

]

=

arr

[

j+

1

]

,

arr

[

j

]

Example array

arr

=

[

64

,

34

,

25

,

12

,

22

,

11

,

90

]

bubble_sort

(

arr

)

print

(

"Sorted array:"

,

arr

)

Code analysis:

  1. bubble_sort The function takes a list arr as its argument.
  2. n is the length of the list.
  3. The outer loop for i in range(n) controls the number of passes; after each pass the largest element is placed in its correct position.
  4. The inner loop for j in range(0, n-i-1) compares adjacent elements and swaps them if the previous one is greater than the next.
  5. Finally, print the sorted array.

Output result:

排序后的数组: [11, 12, 22, 25, 34, 64, 90]

Document Object Reference Manual Python3 Examples