1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| public class Test { public static void main(String[] args) { printArray(arr); bubbleSort(arr); printArray(arr); }
private static final int arr[] = { 3, 8, 7, 2, 1, 5, 6, 9, 0 };
public static void bubbleSort(int[] arr) { int len = arr.length; if (len <= 1) { return; }
for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } } } }
public static void swap(int[] arr, int i, int j) { if (i < 0 || j < 0) { return; }
int len = arr.length; if (i == j || i >= len || j >= len) { return; }
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; }
public static void printArray(int[] arr) { StringBuilder sb = new StringBuilder(); for (int a : arr) { sb.append(a).append(","); } String result = sb.substring(0, sb.length() - 1).toString(); System.out.println(result); }
}
|