結合舞蹈更易理解的演算法--氣泡排序演算法[java程式碼]
阿新 • • 發佈:2019-01-23
舞蹈地址:http://t.cn/hrf58M
氣泡排序演算法java程式碼:
/** * 氣泡排序 * @author hsy * */ public class BubbleSort { private long[] a; private int nElems; public BubbleSort( int max) { super(); this.a = new long[max]; nElems = 0; } /** * 向陣列中插入資料 * @param value */ public void insert(long value){ a[nElems] = value; nElems++; } /** * 列印陣列 * */ public void display(){ for(int i=0;i<nElems;i++){ System.out.print(a[i]+","); } System.out.println(""); } /** * 排序 * */ public void bubbleSort(){ int out; int 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 index1 * @param index2 */ private void swap(int index1,int index2){ long temp = a[index1]; a[index1] = a[index2]; a[index2] = temp; } public static void main(String[] args){ int max = 100; BubbleSort arr = new BubbleSort(max); arr.insert(10); arr.insert(5); arr.insert(45); arr.insert(8); arr.insert(34); arr.insert(78); arr.insert(22); arr.insert(68); arr.insert(82); arr.insert(53); arr.insert(7); arr.insert(99); arr.insert(57); arr.insert(72); arr.display(); long start = System.currentTimeMillis(); arr.bubbleSort(); long end = System.currentTimeMillis(); System.out.println("排序耗時:"+(end-start)); arr.display(); } }
控制檯輸出:
10,5,45,8,34,78,22,68,82,53,7,99,57,72,
排序耗時:0
5,7,8,10,22,34,45,53,57,68,72,78,82,99,