import java.util.*; class BubbleSort { public int[] sort(int[] arr) { int max = arr.length-1; for (int i=0; i < max; i++) { int move = max-i; int tmp; for (int j=0; j < move; j++) { if (arr[max-j] < arr[max-j-1]) { //swap tmp = arr[max-j]; arr[max-j] = arr[max-j-1]; arr[max-j-1] = tmp; } } } return arr; } private static String a2l(int[] arr) { return Arrays.toString(arr); } /* main */ public static void main(String[] args) { int[] arr1 = { 3, 7, 1, 2, 6 }; int[] arr2 = { 6, 1, 12, 3, 4 }; BubbleSort bs = new BubbleSort(); System.out.println(a2l(arr1)); System.out.println(" => " + a2l(bs.sort(arr1))); System.out.println(a2l(arr1)); System.out.println(a2l(arr2)); System.out.println(" => " + a2l(bs.sort(arr2))); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10678.html