FOR LEI LEI

#include <cassert>
#include <cstdio>
#include <cstring>
#include <cstdlib>

int num_cmp(const void * e1, const void * e2)
{
    return (*(int *)e1) - (*(int *)e2);
}

void GetMinMax(const char * input, char * char_tok, int *num_max, int *num_min)
{
    int nCount = 0;
    int nIndex = 0;
    int * num_input;

    int len = strlen(input);
    char *str_input = new char [len];
    char *str_input2 = new char [len];

    strcpy(str_input, input);
    strcpy(str_input2, input);

    char *pch;
    pch = strtok(str_input, char_tok);

    while (pch != NULL)
    {
        ++nCount;
        pch = strtok(NULL, char_tok);
    }


    num_input = new int[nCount];

    pch = strtok(str_input2, char_tok);
    while (pch != NULL)
    {
        *(num_input+nIndex) = atoi(pch);
        ++nIndex;

        pch = strtok(NULL, char_tok);
    }
    assert(nIndex == nCount);

    qsort(num_input, nCount, sizeof(int), num_cmp);

    *num_min = num_input[0];
    *num_max = num_input[nCount-1];

    delete [] num_input;

    delete [] str_input;
    delete [] str_input2;
}

int main()
{
    int num_max;
    int num_min;

    char input[] = "3;9;10;11;1;8;2;4";
    char *char_tok = ";";

    GetMinMax(input, char_tok, &num_max, &num_min);

    printf("min=%d, max=%d\n", num_min, num_max);

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章