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 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| public class BubbleSort { public static void bubbleSort1(int[] a, int n) { int i,j;
for (i=n-1; i>0; i--) { for (j=0; j<i; j++) {
if (a[j] > a[j+1]) { int tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } } } }
public static void bubbleSort2(int[] a, int n) { int i,j; int flag;
for (i=n-1; i>0; i--) {
flag = 0; for (j=0; j<i; j++) { if (a[j] > a[j+1]) { int tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp;
flag = 1; } }
if (flag==0) break; } }
public static void main(String[] args) { int i; int[] a = {20,40,30,10,60,50};
System.out.printf("before sort:"); for (i=0; i<a.length; i++) System.out.printf("%d ", a[i]); System.out.printf("\n");
bubbleSort1(a, a.length);
System.out.printf("after sort:"); for (i=0; i<a.length; i++) System.out.printf("%d ", a[i]); System.out.printf("\n"); } }
|