Skip to content

Instantly share code, notes, and snippets.

@BadUncleX
Last active April 11, 2018 05:41
Show Gist options
  • Save BadUncleX/a09de354ab75a12c9e87a977b8b85d62 to your computer and use it in GitHub Desktop.
Save BadUncleX/a09de354ab75a12c9e87a977b8b85d62 to your computer and use it in GitHub Desktop.
冒泡排序优化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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment