1. I was asked about the simplest bubble sort in the interview today. Bubble sort seems to be simple, but it is not simple. I will review the bubble sort again here.
The time complexity of bubble sort is N squared. If the array is already ordered, it can be optimized. The sort3 method only needs to traverse the array once when the array is in order. The time complexity is N, and the space complexity requires only one int variable. use when exchanging
public void sort1(int[] a) { if (a == null || a.length <= 1) return; for(int i = 0; i < a.length - 1; i++) { // need to do a.length - 1 fake sort for(int j = 0; j < a.length - i - 1; j++) { // Each bubble sort needs to compare a.length-i-1 times if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } } public void sort2(int[] a) { if (a == null || a.length <= 1) return; for(int i = a.length - 1; i > 0; i--) { // need to do a.length - 1 fake sort for(int j = 0; j < i; j++) { // Each bubble sort needs to compare a.length-i-1 times if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } } public void sort3(int[] a) { if (a == null || a.length <= 1) return; for(int i = 0; i < a.length - 1; i++) { // need to do a.length - 1 fake sort boolean isSort = true; // first assume the array is sorted for(int j = 0; j < a.length - i - 1; j++) { // Each bubble sort needs to compare a.length-i-1 times if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; isSort = false; // if swap is performed, the array is unordered } if (isSort) break; // If no swap is performed, the array is already sorted } } }