冒泡排序优化java bubble sort alglrithm
package algorithm_bubble_sort;
// bubble sort 冒泡排序
public class BubbleSort {
public static void bubblesort(int[] a) {
int lastSwap = a.length - 1;
for (int i = 1; i < a.length; i++) {
boolean is_sorted = true;
int currentSwap = -1;
for (int j = 0; j < lastSwap; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
is_sorted = false;
currentSwap = j;
}
}
if (is_sorted) return;
lastSwap = currentSwap;
}
}
public static void main(String[] args) {
int[] a = {2, 5, 1, 8, 4, 3, 23};
bubblesort(a);
for (int i : a) {
System.out.println(i);
}
}
}