1. 程式人生 > >氣泡排序和優化

氣泡排序和優化

冒泡思想:兩兩比較相鄰記錄,內迴圈將最小的數通過交換浮上來。

 

優化思想:設定flag,對已經有序的序列就不繼續判斷了

氣泡排序的實現:

package Bubble_Sort;

//冒泡演算法和改進演算法,正序,從小到大(從1開始)
public class BubbleSort {

    public int[] a=new int[11];
    public int size;
    public int count;
    public boolean flag=true;
    
    public BubbleSort(int[] a)
    {
        
for(int i=0;i<a.length;i++) { this.a[i+1]=a[i]; } size=a.length; } //冒泡演算法 public void bubbleSort() { for(int i=1;i<size;i++) { for(int j=size;j>i;j--) { count++; if(a[j]<a[j-1]) {
int temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; } } } } //冒泡改進演算法 public void bubbleSortImpro() { for(int i=1;i<size&&flag;i++) { flag=false; for(int j=size;j>i;j--) {
if(a[j]<a[j-1]) { count++; swap(a, j, j-1); flag=true; //改變順序則flag=False; } } } } public void traversal() { for(int i=1;i<=size;i++) { System.out.println(a[i]); } } public void swap(int[] arr,int a,int b) { arr[a] = arr[a]+arr[b]; arr[b] = arr[a]-arr[b]; arr[a] = arr[a]-arr[b]; } }

測試:

package Bubble_Sort;

public class App {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a={6,21,3,99,56,44,77,12,7,19};
        int[] b={2,1,3,4,5,6,7,8,9,10};
        BubbleSort bubbleSort=new BubbleSort(a);
//        bubbleSort.bubbleSortImpro();
        bubbleSort.bubbleSort();
        bubbleSort.traversal();
        System.out.println("j改變次數:"+bubbleSort.count);
    }
}

結果:

冒泡法
j改變次數:45

優化方法:
j改變次數:21