【剑指 offer】—— 快速排序

两个辅助函数:

// 生成区间内的随机整数
int RandInRange(int s, int e, unsigned seed=time_t(0))
{ 
    srand(seed);
    return rand()%(e-s)+s;
}

void Swap(int& a, int& b)
{
    int tmp = a; a = b; b = tmp;
}

分区函数:

int partition(int seq[], int len, int start, int end)
{
    if (seq == NULL || len <= 0 || start < 0 || end >= len)
        throw new exception("Invalid parameters");

    int pivot = RandInRange(start, end);
    Swap(seq[pivot], seq[end]);

    int small = start - 1;
    for (int i = start; i < end; ++i)
    {
        if (seq[i] < seq[end])  
        {
            ++small;
            if (small != i)
                Swap(seq[small], seq[i]);
        }
    }
    ++small;
    Swap(seq[end], seq[small]);
    return small;
}

主调函数,由递归结构定义:

void qsort(int seq[], int len, int start, int end)
{
    if (start == end)
        return;
    int idx = partition(seq, len, start, end);
    if (idx > start)
        qsort(seq, len, start, idx-1);
    if (idx < end)
        qsort(seq, len, idx+1, end);
}

你可能感兴趣的:(算法)