Bubble sort: Bubble sort is a simple sort algorithm in the sorting algorithm;
It repeats the sequence of columns from the first element, compares two elements at a time, and, if a[j]>a[j+1] swaps them, knows the last element, so that the largest element of the unordered element "floats" to the top of the sequence, and then the array finishes sorting before the unordered elements are repeated.
Public classBubblesort { Public voidSortinta[]) { inttemp = 0; for(intI=a.length-1; i>0; i--) {//I is the number of elements that are not sorted for(intj=0; j<i; J + +) {//use J to control the comparison size of 22 adjacent elements and "float" the larger elements to the top of the list if(A[j]>a[j+1]) {temp =A[j]; A[J]= A[j+1]; A[j+1] =temp; } } } }}
Bubble sort in the operation of 22 exchange order, there are two for loops outside, so the time complexity is O (n^2), bubble sort required space a[j], a[j+1], temp is fixed, does not change with the length of the array, so the spatial complexity of O (1).
Sorting algorithm Summary (Java) 1: bubbling sort