C#堆排序代碼

b5cw 9年前發布 | 1K 次閱讀 C#

 

private static void Adjust (int[] list, int i, int m)
{
    int Temp = list[i];
    int j = i * 2 + 1;

while (j <= m)
{
    //more children
    if(j < m)
        if(list[j] < list[j + 1])
            j = j + 1;

    //compare roots and the older children
    if(Temp < list[j])
    {
        list[i] = list[j];
        i = j;
        j = 2 * i + 1;
    }
    else
    {
        j = m + 1;
    }
}

list [i] = Temp;

} public static void HeapSort (int[] list) { //build the initial heap for (int i = (list.Length - 1) / 2; i > = 0; i-) Adjust (list, i, list.Length - 1);

//swap root node and the last heap node
for (int i = list.Length - 1; i > = 1; i-)
{
    int Temp = list [0];
    list [0] = list [i];
    list [i] = Temp;
    Adjust (list, 0, i - 1);
}

}</pre>

 本文由用戶 b5cw 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!