본문 바로가기
프로그래머스

[프로그래머스/C] 특이한 정렬

by jonnwon 2024. 6. 21.
728x90
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/120880

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int compare(const int *a, const int *b, const int *n) {
    int d1 = abs(*n - *a);
    int d2 = abs(*n - *b);
    
    if (d1 == d2) {
        return *b - *a;
    }
    else {
        return d1 - d2;
    }
}

int* solution(int numlist[], size_t numlist_len, int n) {
    int* answer = (int*)malloc(sizeof(int) * numlist_len);
    
    for (int i = 0; i < numlist_len; i++) {
        answer[i] = numlist[i];
    }
    qsort_r(answer, numlist_len, sizeof(int), compare, &n);    
    return answer;
}

 

 

 

qsort_r 함수

void qsort_r(void *base, size_t nmemb, size_t size,
             int (*compar)(const void *, const void *, void *),
             void *arg);

qsort_r 함수는 qsort 함수와 비슷하게 배열을 정렬하지만, 추가적인 인자를 비교 함수에 전달할 수 있다.

 

 

compare 함수

  1. d1과 d2는 각각 첫 번째 요소와 두 번째 요소들의 n과의 거리다.
  2. 만약 두 거리 d1과 d2가 같다면, 두 요소 중 더 큰 숫자가 앞에 오도록 한다. (*b - *a를 반환)
  3. 두 거리가 다르면, 더 가까운 거리에 있는 요소가 앞에 오도록 한다. (d1 - d2를 반환)
728x90