第7章 排序

// 交换类排序

void QuickSort(Elem R[], int n)
{
    QSort(R, 1, n);
}

void QSort(Elem R[], int low, int high)
{
    if (low < high)
    {
        pivotloc = Partition(R, low, high);
        QSort(R, low, pivotloc - 1);
        QSort(R, pivotloc + 1, high);
    }
}



int Partition(Elem R[], int low, int high)
{
    pivotkey = R[low].key;
    while(low < high)
    {
        while(low < high && R[high].key >= pivotkey)
            high--;
        R[low]<-->R[high];

        while(low < high && R[high].key <= pivotkey)
            low++;
        R[low]<-->R[high];
    }

    return low;
}









// 选择排序
// 堆排序


void HeapSort(HeapType &h)
{
    for(i = h.length/2; i > 0; i--)
        HeapAdjust(h, i, h.length);
    for(i = h.length; i > 1; i--)
    {
        h.r[1] <-->h.r[i];
        HeapAdjust(h, 1, i - 1);
    }
}





void HeapAdjust(HeapType &h, int s, int m)
{
    rc = h.r[s];
    for(j = 2*s; j <= m; j *= 2)
    {
        if(j < m && h.r[j].key < h.r[j+1].key)
            j++;
        if(!(rc.key < h.r[j].key))
            break;
        h.r[s] = h.r[j];
        s = j;
    }
    h.r[s] = rc;
}

你可能感兴趣的:(第7章 排序)