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

Python Bubble Sort

Python Bubble Sort

Document Object Reference Manual Python3 Examples

Bubble sort is a simpleexchange sorting algorithm; its core working principle is:

  1. repeatedly traverse the list to be sorted, each time comparingtwo adjacent elements;
  2. if the two elements are out of order (for example, in an ascending sort the previous element is greater than the next), thenswap their positions;
  3. each pass bubbles thelargest element of the current unsorted part to the end(in the ascending case), just like bubbles rising;
  4. repeat the above process until the whole list is fully sorted (no swaps occur or all elements have been traversed).

Key characteristics

Example

def

bubbleSort

(

arr

)

:

n

=

len

(

arr

)

Traverse all array elements

for

i

in

range

(

n

)

:

The last i elements are already in their correct positions (no need to compare again)

for

j

in

range

(

0

,

n

i

1

)

:

if

arr

[

j

]

arr

[

j

1

]

:

arr

[

j

]

,

arr

[

j

1

]

=

arr

[

j

1

]

,

arr

[

j

]

arr

=

[

64

,

34

,

25

,

12

,

22

,

11

,

90

]

bubbleSort

(

arr

)

print

(

"

Sorted array:

"

)

for

i

in

range

(

len

(

arr

)

)

:

print

(

"

%d

"

%

arr

[

i

]

)

,

The output of the code above is:


Sorted array:
11
12
22
25
34
64
90

Document Object Reference Manual Python3 Examples