1. 程式人生 > >冒泡演算法及優化

冒泡演算法及優化

原版冒泡

private static void sort(int array[])
{
    int tmp  = 0;
    for(int i = 0; i < array.length; i++)
    {
        for(int j = 0; j < array.length - i - 1; j++)
        {
            if(array[j] > array[j+1])
            {
                tmp = array[j];
                array[j] = array[j+1];
                array[j+1] = tmp;
            }
        }
    }
}
public static void main(String[] args){
    int[] array = new int[]{5,8,6,3,9,2,1,7};
    sort(array);
    System.out.println(Arrays.toString(array));
}

優化第一版

private static void sort(int array[])
{
    int tmp  = 0;    
    for(int i = 0; i < array.length; i++)
    {        //有序標記,每一輪的初始是true
        boolean isSorted = true;        
        for(int j = 0; j < array.length - i - 1; j++)
        {            
            if(array[j] > array[j+1])
            {
                tmp = array[j];
                array[j] = array[j+1];
                array[j+1] = tmp;
                //有元素交換,所以不是有序,標記變為false
                isSorted = false;
            }
        }        
        if(isSorted)
        {            
            break;
        }
    }
}
public static void main(String[] args)
{    
    int[] array = new int[]{5,8,6,3,9,2,1,7};
    sort(array);
    System.out.println(Arrays.toString(array));
}

優化第二版

private static void sort(int array[])
{
    int tmp  = 0;
    //記錄最後一次交換的位置
    int lastExchangeIndex = 0;
    //無序數列的邊界,每次比較只需要比到這裡為止
    int sortBorder = array.length - 1;
    for(int i = 0; i < array.length; i++)
    {
        //有序標記,每一輪的初始是true
        boolean isSorted = true;
        for(int j = 0; j < sortBorder; j++)
        {
            if(array[j] > array[j+1])
            {
                tmp = array[j];
                array[j] = array[j+1];
                array[j+1] = tmp;
                //有元素交換,所以不是有序,標記變為false
                isSorted = false;
                //把無序數列的邊界更新為最後一次交換元素的位置
                lastExchangeIndex = j;
            }
        }
        sortBorder = lastExchangeIndex;
        if(isSorted)
        {
            break;
        }
    }
}

public static void main(String[] args)
{
    int[] array = new int[]{3,4,2,1,5,6,7,8};
    sort(array);
    System.out.println(Arrays.toString(array));
}