Bubble Sort (Bubble Sort, translated from Taiwan as: Bubble Sort or Bubble Sort) is a simple sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted. The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the array through exchange. The operation of the bubble sort algorithm is as follows:
1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
3. Repeat the above steps for all elements except the last one.
4. Continue repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.
Code:
#!/usr/bin/env python #-*-encoding:utf-8 #BubbleSort def bubble_sort(param): p_len = len(param) for i in range(p_len): for j in range(i+1,p_len)[::-1]: if param[j] < param[j-1]: param[j],param[j-1]=param[j-1],param[j] return param def main(): param = [1,2,3,5,7,6,4] print bubble_sort(param) if __name__=="__main__": main()