ITeye博客

Java冒泡排序代码整理

haiyang08101 · 2010-11-30 19:36 · java · 编程语言 · Java · J# · Markdown

package com /**

  • 冒泡排序
  • @since jdk1.5及其以上
  • @author 大海
  • @version 1.0
  • @date 2010.02.18

/ public class BubbleSort { /*
* @param args
*/
public static void main(String[] args) {
int maxSize = 100;
BubbleSort bs = new BubbleSort(maxSize);

    bs.insert(10);   
    bs.insert(9);   
    bs.insert(8);   
    bs.insert(7);   
    bs.insert(6);   
    bs.insert(5);   
    bs.insert(4);   
    bs.insert(3);   
    bs.insert(2);   
    bs.insert(1);   

    bs.output(); // 原始输出   
    bs.bubbleSort(); // 排序   
    bs.output(); // 排序输出   

}   

private long[] a; // 整型数据容器   
private int nElems; // 元素个数   

/**  
 * 构造方法  
 *   
 * @param maxSize  
 */  
public BubbleSort(int maxSize) {   
    a = new long[maxSize];   
    nElems = 0;   
}   

/**  
 * 容器放入数据  
 *   
 * @param value  
 */  
public void insert(long value) {   
    a[nElems++] = value;   
}   

/**  
 * 输出容器数据  
 */  
public void output() {   
    for (int j = 0; j < nElems; j++) {   
        System.out.print(a[j] + " ");   
    }   
    System.out.println("");   
}   

/**  
 * 冒泡排序  
 */  
public void bubbleSort() {   
    int out, in;   

    for (out = nElems - 1; out > 1; out--) {   
        for (in = 0; in < out; in++) {   
            if (a[in] > a[in + 1]) {   
                swap(in, in + 1);   
            }   
        }   
    }   
}   

/**  
 * 交换  
 *   
 * @param in  
 * @param i  
 */  
private void swap(int one, int two) {   
    long temp = a[one];   
    a[one] = a[two];   
    a[two] = temp;   
}   

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。