排序算法之交換排序-冒泡排序與快速排序

1.冒泡排序

1.1 算法思想

1.1.1 首先將第一個記錄和第二個記錄進行比較,若爲逆序則交換交換兩個記錄。然後比較第二個記錄和第三個記錄。以此類推。以上過程稱爲第一趟排序,其結果使最大的記錄被安置到最後一個位置。

1.1.2 然後進行第二趟排序,其結果使次大的記錄被安置到第n-1個位置

1.1.3 重複上述操作,直至排序完成

1.2 算法圖解

 

 

1.3 代碼與結果

public class BubbleSort {
    public static void main(String[] args) {
        int a[]={49,38,65,97,76,13,27,49};
        Bsort(a);
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
    }
    public static void Bsort(int a[])
    {
        for(int i=0;i<a.length;i++)
        {
            for(int j=1;j<a.length-i;j++)
            {
                if(a[j-1]>a[j])
                {
                    swap(a,j-1,j);
                }
            }
        }
    }
    public static void swap(int a[],int i,int j)
    {
        int temp=a[i];
        a[i]=a[j];
        a[j]=temp;
    }
}
13 27 38 49 49 65 76 97 

1.4 總結

1.4.1 平均時間複雜度O(n2),空間複雜度O(1);

1.4.2 是穩定排序

 

2.快速排序

2.1 算法思想

2.1.1 選擇待排序表中的第一個記錄作爲樞軸,並記錄此樞軸的值temp,並附設兩個指針low,high分別指向表的上界和下界

2.1.2 從表的最右側依次向左搜索,找到第一個關鍵字小於temp的記錄,將其移到low處

2.1.3 從表的最左側依次向右搜索,找到第一個關鍵字大於temp的記錄,將其移到high處

2.1.4 重複步驟2和3,直至low與high相等。此時low或high的位置即爲樞軸在此趟排序中的最終位置,原表被分爲兩個子表。

2.2 算法圖解

 

2.3 代碼與結果

public class QuickSort {

    public static void main(String[] args) {
        int a[]={49,38,65,97,76,13,27,49};
        Qsort(a,0,a.length-1);
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
    }

    public static void Qsort(int a[],int low,int high)
    {
        if(low<high)
        {
            int posLoc = partition(a,low,high);
            Qsort(a,low,posLoc-1);
            Qsort(a,posLoc+1,high);
        }
    }

    public static int partition(int a[],int low,int high)
    {
        int temp=a[low];
        while(low<high)
        {
            while(low<high&&a[high]>temp) high--;
            a[low]=a[high];
            while (low<high&&a[low]<temp) low++;
            a[high]=a[low];
        }
        a[low]=temp;
        return  low;
    }

}
13 27 38 49 49 65 76 97 

2.4 總結

2.4.1 平均時間複雜度O(nlogn)

2.4.2 最大遞歸調用次數與遞歸樹的深度一致,最好的空間複雜度爲(logn),最壞的空間複雜度爲O(n)

2.4.3 是不穩定排序,適合初始記錄無序,n較大的情況

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章