新用户登入 登录
萌子岛 返回首页

yh0603126的个人空间 https://www.dommdo.com/?1128695 [收藏] [复制] [RSS]

日志

Java 1

已有 157 次阅读2012-11-22 17:24 | Java

01package algorithm;
02 
03public class BubbleSort {
04 
05     
06 
07    // 冒泡排序1
08    public static void bubbleSort1(int[] a, int n) {
09        for (int i = 0; i < n; i++) {
10            for (int j = 1; j < n - i; j++) {
11                if (a[j - 1] > a[j]) {
12                    swap(a, j - 1, j);
13                }
14            }
15        }
16    }
17 
18    // 冒泡排序2
19    //下面对其进行优化,设置一个标志,如果这一趟发生了交换,则为true,
20    //否则为false。明显如果有一趟没有发生交换,说明排序已经完成。
21    public static void bubbleSort2(int[] a, int n) {
22        boolean flag = true;
23        while(flag) {
24            flag = false;
25            for (int i = 0; i < n; i++) {
26                for (int j = 1; j < n - i; j++) {
27                    if (a[j - 1] > a[j]) {
28                        swap(a, j - 1, j);
29                        flag = true;
30                    }
31                }
32            }
33        }
34    }
35    // 冒泡排序3
36    public static void bubbleSort3(int[] a, int n) {
37        int flag = n;
38        while(flag > 0) {
39            flag = 0;
40            for (int i = 0; i < n; i++) {
41                for (int j = 1; j < n - i; j++) {
42                    if (a[j - 1] > a[j]) {
43                        swap(a, j - 1, j);
44                        flag = j;
45                    }
46                }
47            }
48        }
49    }
50 
51    public static void main(String[] args) {
52 
53        int max = 10;
54        int[] a = { 2, 4, 1, 5, 7, 6, 1, 9, 0, 2 };
55        printArray(a, max);
56        bubbleSort3(a, max);
57        printArray(a, max);
58        bubbleSort1(a, max);
59        printArray(a, max);
60        bubbleSort2(a, max);
61        printArray(a, max);
62         
63    }
64     
65    private static void printArray(int[] a, int n) {
66        for (int i = 0; i < n; i++) {
67            System.out.print(a[i] + " ");
68        }
69        System.out.println();
70    }
71 
72    private static void swap(int a[], int x, int y) {
73        int t = a[x];
74        a[x] = a[y];
75        a[y] = t;
76    }
77}

路过

雷人

握手

鲜花

鸡蛋

全部作者的其他最新日志

评论 (0 个评论)

小黑屋|萌子岛

GMT+8, 2025-5-1 20:59 , Processed in 0.050277 second(s), 18 queries , Gzip On, MemCache On.

Copyright 2020  atollmoe©.a2.1.0 All rights reserved. 9+

Copyright 2009  supported by zhixuan© oeo© oko© All rights reserved.Thank you!

返回顶部