2011年3月22日星期二

Quick Sort 快排

void quickSort(int* a, int start, int end)
{
    if(start == end)
        return;
    int key = a[start];
    int keyIndex = start;
    int i = start, j = end;
    int backward = 1;
    int temp;
    while(i != j)
    {
        if(backward)
        {
            for(; j > i; j--)
            {
                if(a[j] < key)
                {
                    temp = a[j];
                    a[j] = a[i];      //a[i]  == key
                    a[i] = temp;
                    keyIndex = j;
                    break;
                }
            }
            backward = 0;
        }
        else
        {
            for(; i < j; i++)
            {
                if(a[i] > key)
                {
                    temp = a[j];       //a[j]  == key
                    a[j] = a[i];
                    a[i] = temp;
                    keyIndex = i;
                    break;
                }
            }
            backward = 1;
        }
    }
    quickSort(a, start, keyIndex);
    if(keyIndex != end)
        quickSort(a, keyIndex + 1, end);
}

没有评论:

发表评论