Python algorithm-python implements the bubble sorting
Principles of bubble sorting:
Compares adjacent elements. If the first is bigger than the second, exchange the two of them.
Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
Repeat the preceding steps for all elements except the last one.
Continue to Repeat the above steps for fewer and fewer elements until there is no need to compare them.
Instance code
#-*-Encoding: UTF-8 -*-
Def bubble_sort (seq, cmp = cmp ):
"Bubble sorting, the pseudo code is as follows:
BUBBLESORT ()
1 for I limit 1 to length [A]
2 do for j specify length [A] downto I + 1
3 do if A [j] <A [j-1]
4 then exchange A [j] A [j-1]
T (n) = θ (n ^ 2)
Args:
Seq (Sequence): a Sequence object.
Cmp (Function): comparison Function. The default value is the built-in function cmp ().
Returns:
A sorted list.
"""
If (seq = None ):
Return None
Length = len (seq)
For I in range (length ):
For j in range (length-1, I,-1 ):
If seq [j] <seq [j-1]:
Seq [j], seq [j-1] = seq [j-1], seq [j]
Return seq
If _ name _ = '_ main __':
Import random, timeit
Items = range (1, 10000)
Random. shuffle (items)
Def test_sorted ():
Print (items)
Sorted_items = sorted (items)
Print (sorted_items)
Def test_bubble_sort ():
Print (items)
Sorted_items = bubble_sort (items)
Print (sorted_items)
Test_methods = [test_sorted, test_bubble_sort]
For test in test_methods:
Name = test. _ name _ # test. func_name
T = timeit. Timer (name + '()', 'from _ main _ import '+ name)
Print (name + 'takes time: % f' % t. timeit (1 ))