Bubble Sort
I. INTRODUCTION
Bubble Sort (Bubble Sort) is also a simple and intuitive sorting algorithm. It repeatedly visited the number of columns to be sorted, a comparison of two elements, if they put them in the wrong order switching over. The number of visits to the column work is repeated until there is no longer need to swap, that is to say the number of columns already sorted completed. The origin of the name of the algorithm is because the smaller elements will slowly through the exchange of "float" to the top of the columns.
As one of the simplest sorting algorithms, feeling bubble sort I feel like Abandon word appears in the book, like, every time on the first page first, so the most familiar. There is also a bubble sort algorithm optimization is to set up a flag, when the element does not occur in the exchange trip traversal sequence, then prove that the sequence has been ordered.
Second, the algorithm steps
Do the same work for each pair of adjacent elements, from the beginning to the end of the first to the last pair. Once this is done, the last element is the biggest number. Repeat these steps for all elements, except the last one. Continued to repeat the above steps for each time fewer and fewer elements, a pair of numbers until there is no need to compare.
Third, issues
1. When did the fastest
When the input data is already positive sequence (it has a positive sequence, and I would also like you bubble sort what is the use ah) .
2. When the slowest
When the data is entered in reverse order (write a for loop in reverse order output data is not on the line, why use your bubble sort it).
Fourth, code implementation
python version
# Bubble sort, the time complexity of O (N²) DEF bubble_sort (NUM): "" " If a sort bubble sort is no exchange takes place, then the list has been ordered, it can directly end the algorithm : param NUM: : return : "" " for I in Range (len (NUM) -. 1 ): Exchange = False Print (NUM) for J in Range (len (NUM) -. 1 - I): IF NUM [J]> NUM [J +. 1 ]: NUM [J], NUM [J +. 1] NUM = [J +. 1 ], NUM [J] Exchange = True IF Not exchange: return num return num l = [33, 11, 12, 1, 2, 3, 4, 5, 22] print(bubble_sort(l))
JavaScript version
function bubbleSort (ARR) { var len = arr.length; for ( var I = 0; I <len -. 1; I ++ ) { for ( var J = 0; J <len -. 1 - I; J ++ ) { IF (ARR [J]> ARR [J +. 1]) { // neighboring elements twenty-two Comparative var TEMP = ARR [J +. 1]; // element exchange ARR [J +. 1] = ARR [J]; ARR [J] = TEMP; } } } return ARR; }
Golang version
func bubbleSort(arr []int) []int { length := len(arr) for i := 0; i < length; i++ { for j := 0; j < length-1-i; j++ { if arr[j] > arr[j+1] { arr[j], arr[j+1] = arr[j+1], arr[j] } } } return arr }