#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define SIZE 10
void bubble(int*, const int, int(*)(int, int));
int ascending(const int, const int);
int descending(const int, const int);
int main()
{
int a[SIZE] = { 2,6,4,8,10,12,89,68,45,37 };
int counter, order;
printf("오름차순 정렬은 1, 내림차순 정렬은 2를 누르세요 : ");
scanf("%d", &order);
printf("\n 원래 데이터 \n");
for (counter = 0; counter < SIZE; counter++)
{
printf("%4d", a[counter]);
}
if (order == 1)
{
bubble(a, SIZE, ascending);
printf("\n 오름차순으로 정렬된 데이터 \n");
}
else
{
bubble(a, SIZE, descending);
printf("\n 내림차순으로 정렬된 데이터 \n");
}
for (counter = 0; counter < SIZE; counter++)
{
printf("%4d", a[counter]);
}
putchar('\n');
return 0;
}
void bubble(int* work, const int size, int(*compare)(int, int))
{
int pass, count;
void swap(int*, int*);
for (pass = 1; pass <= size - 2; pass++)
{
for (count = 0; count <= size -2; count++)
if ((*compare)(work[count], work[count + 1]))
{
swap(&work[count], &work[count + 1]);
}
}
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int ascending(const int a, const int b)
{
return b < a;
}
int descending(const int a, const int b)
{
return a < b;
}
ascending 를 매개변수로 사용하여, 사용자 정의함수 ascending를 호출하는 거라고 생각 했는데 int ascending(const int a, const int b) 에서 어떤 매개변수를 받아서 a 와 b가 입력된거고,
b < a; 라고 리턴시키면 사용자 정의 bubble 함수의 int(*compare)(int, int) 에 어떤식으로 전달되는건지 이해가 잘 안가는데 설명좀 부탁드립니다.
생각한거 맞는데ㅇㅅㅇ
int ascending(const int a, const int b) 에서 어떤 매개변수를 받아서 a 와 b가 입력된거고, b < a; 라고 리턴시키면 사용자 정의 bubble 함수의 int(*compare)(int, int) 에 어떤식으로 전달되는건지가 궁금해서요 ㅠㅠ
함수포인터 검색
(*compare)(work[count], work[count + 1])는 ascending(work[count],work[count+1])와 같다. 결국 if ((*compare)(work[count], work[count + 1])) == if (work[count + 1] < work[count])와 같다.