Programming Language/C,C++

C, C++] 함수를 인자값으로 활용하기

TwinParadox 2016. 7. 21. 13:44
728x90

함수를 인자값으로 활용하여

전달된 함수에 따라 내림차순과 오름차순 정렬을 시행하게 하는 프로그램

어지간한 과제는 그냥 무난하게 했는데 이번 건 보고 조금 당황.

함수를 인자값으로 쓰는 일이 드물다 보니까, 처음에 보고 좀 난해했음.

사용된 정렬은 삽입정렬(Insertion Sort)


 

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
31
32
#include <stdio.h>
#include <stdlib.h>
 
#define TRUE 1
#define FALSE 0
 
typedef int element;
 
int ascend(element x, element y)
{
    if (x < y)
        return FALSE;
    return TRUE;
}
int descend(element x, element y)
{
    if (x > y)
        return FALSE;
    return TRUE;
}
void InsertionSort(element list[], int n, int (*func)(intint))
{
    element key;
    int i, j;
    for (i = 1; i < n; i++)
    {
        key = list[i];
        for (j = i - 1; j >= 0 && func(list[j],key); j--)
            list[j + 1= list[j];
        list[j + 1= key;
    }
}
cs


728x90
728x90