[C] 백준 1427 - 소트인사이드

메르센고수·2023년 8월 12일
0

Baekjoon

목록 보기
14/48

문제 - 소트인사이드 (Silver 5)

풀이 전략

  • compare 함수를 선언해서 qsort로 내림차순 정렬을 한다
  • 문자열을 입력받아서 정렬한 수를 새로운 배열에 저장을 하는데, 길이가 정해져 있지 않으므로 동적할당으로 정렬한 수를 저장한다.

참고

qsort 함수

  • 기본구조
void qsort (void *base, size_t len, size_t width, int (*compare)(const void *, const void *);

-base: 정렬하고자 하는 배열
-len : 배열의 원소의 수
-width : 배열에서 원소 하나의 크기
-compare : 함수 포인터

int compare(const void *a, const void *b){
    int num1=*(int*)a; // 역참조하여 void 포인터 a 값을 int형으로 가져옴
    int num2=*(int*)b; // 역참조하여 void 포인터 b 값을 int형으로 가져옴 

    if(num1<num2){
    	return -1;
    } // 내림차순 정렬
    if(num1>num2){
    	return 1;
    } // 오름차순 정렬
    return 0;
}

오름 차순과 내림 차순을 조금 더 간단하게 구현해보면, 아래와 같이 구현해볼 수 있다.

int compare(const void *a, const void *b)
{
    return *(int*)a-*(int*)b;    // 오름차순
}
int compare(const void *a, const void *b)
{
    return *(int*)b-*(int*)a;    // 내림차순
}

소스 코드

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

int compare(const void *a, const void *b){
    int num1=*(int*)a;
    int num2=*(int*)b;

    return num2-num1;
}
int main(){
    char word[10000];
    scanf("%s",word);

    int len=strlen(word);
    int* arr=(int*)malloc(sizeof(int)*len); // 정렬된 수를 저장하기 위해 동적할당한 arr 배열

    for(int i=0;i<len;i++){
        arr[i]=word[i]-'0'; // word는 char형이므로 int형으로 변환
    }

    qsort(arr,len,sizeof(int),compare); // 내림차순 정렬
    
    for(int i=0;i<len;i++){
        printf("%d",arr[i]);
    }
    free(arr); // 동적할당한 메모리영역 해제
    return 0;
}

결과

결론

함수포인터에 대한 이해가 필요할 것 같다...

profile
블로그 이전했습니다 (https://phj6724.tistory.com/)

0개의 댓글