본문 바로가기
프로그래머스코딩테스트연습풀이/C언어

[프로그래머스/C언어] 뒤에서 5등까지

by 코코쵸마 2023. 8. 5.

문제

정수로 이루어진 리스트 num_list가 주어집니다. num_list에서 가장 작은 5개의 수를 오름차순으로 담은 리스트를 return하도록 solution 함수를 완성해주세요.

 

솔루션

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

// num_list_len은 배열 num_list의 길이입니다.
int* solution(int num_list[], size_t num_list_len) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    int* answer = (int*)malloc(5 * sizeof(int));
    int tmp;
    for(int i = 0; i < num_list_len - 1; i++)
        for(int j = i + 1; j < num_list_len; j++){
            if(num_list[i] > num_list[j]){
                tmp = num_list[i];
                num_list[i] = num_list[j];
                num_list[j] = tmp;
            }
        }
    for(int k = 0; k < 5; k++)
        answer[k] = num_list[k];
    return answer;
}

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