2012年8月25日 星期六

[C++] Sample for Using stdlib to implement Extend Quick Sort function

As last example, I use standard library to implement quick sort again.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>

void quickSortEx(int[], int, bool, int, int);
int cmp(const void* a, const void* b);

int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
    const int count = 10;
    int number[count] = {0};

    printf("Before: ");
    int i;
    for(i = 0; i < count; i++) {
        number[i] = rand() % 100;
        printf("%d ", number[i]);
    }
    printf("\n");

    quickSortEx(number, count, true, 0, count-1);

    printf("Afer: ");
    for(i = 0; i < count; i++)
        printf("%d ", number[i]);

    printf("\n");
    return 0;
}

void quickSortEx(int number[], int count, bool desc, int left, int right)
{
    qsort(number, count, sizeof(number[0]), cmp);

    if (desc)
        std::reverse(number, number+count);
}

int cmp(const void* a, const void* b)
{
    const int x = *static_cast<const int*>(a);
    const int y = *static_cast<const int*>(b);

    if (x == y)
        return 0;

    return x > y ? 1 : -1;
}


Reference:
http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
http://www.cplusplus.com/reference/algorithm/reverse/

沒有留言:

張貼留言