Bubble Sort 氣泡排序法 [大氣泡受到的浮力最大會首先冒出來]

 

重複由左邊掃描到右邊,將兩兩相鄰的元素比較,如果是左邊元素比右邊元素大即需要交換,最大的元素就會被換至最右邊。

 


public class Sort 
{
    public static void main(String[] args) 
    {
        int a [] = {5, 9, 3, 10, 6};


        Bubble_Sort(a);

 

        // show the element
        for(int i = 0; i < a.length; i++)
        {
            System.out.print(a[i] + " ");
        }
    }
    
    public static void Bubble_Sort(int a[])
    {
        int i, j, temp, count_compare = 0, count_swap = 0;


        for(i = a.length - 1; i > 0; i--)           // i 是 range
        {
            for(j = 0; j < i; j++)                      // j 是每個比較的左方 ,j+1是右方
            {
                count_compare ++;
                if(a[j] > a[j + 1])                       // 左邊大右邊小就要交換
                {
                    count_swap ++ ;
                    temp = a[j];                          //將a[j] 和 a[j + 1] 交換
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        System.out.println("count_compare: " + count_compare);
        System.out.println("count_swap: " + count_swap);
    }
}

 


 

輸出結果:

 

count_compare: 10
count_swap: 4
3 5 6 9 10 

arrow
arrow
    文章標籤
    sort bubble sort
    全站熱搜

    smallone 發表在 痞客邦 留言(0) 人氣()