排序之自底向上?自頂向下?--C++

看着算法書有點懵T_Thtml

參照https://blog.csdn.net/u011197534/article/details/78368580算法

自頂向下便是歸併排序,參考我以前的歸併排序,如圖數組

 

自底向上,就是兩兩歸併、四四歸併、88歸併,以下圖:spa

 書上的僞代碼:.net

/*
輸入:n個元素的數組A[1...n]
輸出:按非降序排列的數組A[1...n]
t <- 1
while t < n
    s <- t; t <- 2s; t <- 0
    while i+t <= n
        merge(A, i+1, i+s, i+t)
        i <- i+t
    end while
    if i+s < n then merge(A, i+1, i+s, n)
end while
*/

完整代碼:code

void merge(int A[], int l, int mid, int r)
{

    int help[r-l+1];  //輔助數組
    int i = 0;
    int lIndex = l;
    int rIndex = mid + 1;
    while(lIndex<=mid && rIndex<=r)
    {
        help[i++] = A[lIndex] < A[rIndex] ? A[lIndex++] : A[rIndex++];
    }
    while(lIndex<=mid)
    {
        help[i++] = A[lIndex++];
    }
    while(rIndex<=r)
    {
        help[i++] = A[rIndex++];
    }
    for(i = 0; i < r-l+1; i++)
    {
        A[l+i] = help[i];
    }
    
}

void downUpSort(int A[], int n)
{
    int i = 1;
    while(i < n)  //for(int i=1; i<n; t = 2 * i)
    {
        int s = i;
        i = 2 * s;  //歸併子數組序列擴大一倍
        int j = 0;
        //子區間歸併
        while(i+j <= n)  //for(int j = 0; j < n-i; j = j+2*i)
        {
            merge(A, j, j+s-1, j+i-1);
            j = j+i;
        }
        if(j+s < n)
            merge(A, j, j+s-1, n-1);
    }
}

int main()
{
    int A[9] = {5,4,8,2,9,3,1,6,7};
    cout << "before sort: ";
    for (int i = 0; i < 9; i++)
        cout << A[i] << " ";
    cout << endl;
    downUpSort(A, 9);
    cout << "after sort: ";
    for (int i = 0; i < 9; i++)
        cout << A[i] << " ";
    cout << endl;
}

結果以下:htm

相關文章
相關標籤/搜索