달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

'삽질예방/표준 API'에 해당되는 글 2

  1. 2008.02.17 bsearch()
  2. 2008.02.17 qsort()
2008. 2. 17. 22:50

bsearch() 삽질예방/표준 API2008. 2. 17. 22:50

qsort에 이어 매우 유용한 서치 api, 물론 stdlib.h만 필요하다.

원형
       #include <stdlib.h>

       void *bsearch(const void *key, const void *base, size_t nel,
              size_t width, int (*compar)(const void *, const void *));

qsort와 거의같지만, 찾고자 하는 key변수가 추가 되었다.  못찾으면 NULL을 리턴한다.(매우 직관적이지 아니한가.)

코드
int IntCmpAsc(const void* a, const void* b);

int main(void)
{
    int a[10];
    int key;    // to find

    int* p;

    for (int i = 0; i < 10; i++)
        printf("%10p ", &a[i]);
    putchar('\n');
    for (int i = 0; i < 10; i++)
        printf("%10d ", a[i] = i);
    putchar('\n');

    key = 9;
    p = (int*)bsearch(&key, a, 10, sizeof(int), IntCmpAsc);

    if (p == NULL)
        printf("couldn't find.\n");
    else
        printf("found = %d, %p\n", *p, p);

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

int IntCmpAsc(const void* a, const void* b)
{
    return *(int*)a - *(int*)b;
}


결과
0xbf8cff6c 0xbf8cff70 0xbf8cff74 0xbf8cff78 0xbf8cff7c 0xbf8cff80 0xbf8cff84 0xbf8cff88 0xbf8cff8c 0xbf8cff90
         0          1          2          3          4          5          6          7          8          9
found = 9, 0xbf8cff90



복잡한 숫자들은 배열의 주소와 포인터값이다.

:
Posted by Kwang-sung Jun
2008. 2. 17. 22:46

qsort() 삽질예방/표준 API2008. 2. 17. 22:46

qsort()는 stdlib.h에 속해 있으므로 매우 접근성도 좋고 성능도(?) 어느정도 입증되었으리라는 추측이다.

원형은
       #include <stdlib.h>

       void qsort(void *base, size_t nel, size_t width,
              int (*compar)(const void *, const void *));

base는 대상 배열, nel은 num of element, width는 각 항목의 크기(바이트), 마지막은 비교 함수이다.

다음은 사용예이다.

int IntCmp(const void* a, const void* b)
{
    return *(int*)a - *(int*)b;
}

int main(void)
{
    int abc[15];
    srand(time(NULL));

    for (int i = 0; i < 15; i++) {
        printf("%10d", abc[i] = rand() % 100);
    }

    qsort(abc, 15, sizeof(int), IntCmp);

    printf("\n\n");
    for (int i = 0; i < 15; i++) {
        printf("%10d", abc[i]);
    }
    putchar('\n');
    return 0;
}


결과는

deltakam@deltakam-laptop:~/netflix_prize/tmp/qsort$ ./a.out
        34         1        89         9        80        75        84        23        46        28         4        69        30        92        41

         1         4         9        23        28        30        34        41        46        69        75        80        84        89        92



다음은 float를 비교할 경우에 대비하여 작성한 것이며 테스트를 통과한 것이다.
int FloatCmp(const void* a, const void* b)
{
   float det = *(float*)a < *(float*)b;

   if (det < 0.0)
       return -1;
   else if (det > 0.0)
       return 1;
   else
       return 0;
}

:
Posted by Kwang-sung Jun