Ideas:
- Two elements relatively large place to the right
- From the beginning in order compare two adjacent elements, the purpose is to find the largest element into the end, this element is no longer involved Compare
- The second still from scratch, the second largest element in the correct position
- Compare a total of len -1 times, as it has been determined the position len -1 elements, then the n-th is certainly the smallest that
- Comparison of the number of times i is len - i -1, and the next because every time a comparison element
- When the two elements are not switched, the sorting algorithm is stable
- Optimization: When a trip without any exchange, explained that it had ordered the
Sort of 2,5,1,6,9,3
Algorithm:
/**
* 冒泡排序
*/
public class Solution {
public static void bubbleSort(int[] array) {
boolean swap; // 优化
for (int i = 0; i < array.length; i++) {
swap = false;
// i 从第 0 次开始,没一趟都会少比较一个元素
// -1 表示比较次数少于元素个数
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swap = true;
}
}
if (swap = false) {
break;
}
}
}
public static void main(String[] args) {
int[] array = new int[]{2, 5, 1, 6, 9, 3};
bubbleSort(array);
for (int i : array) {
System.out.print(i + " "); // 1 2 3 5 6 9
}
}
}