코딩테스트 - 문자열 정렬하기, C 언어, 버블정렬 활용

728x90
반응형

주어진 문자열을 소문자에서 대문자 순서로 정렬하라.

 

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
char* solution(const char* s) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    
    int len = strlen(s);
    char temp;
    char* answer = (char*)malloc((sizeof(char) * len));

    strcpy(answer, ""); // answer clear
    strcpy(answer, s);
    
    for (int i = 0; i < len; i++) { // bubble sort
        for (int j = 0; j < ((len - 1) - i); j++) {
            if (answer[j] < answer[j + 1]) {	 // > 오름차순, < 내림차순 
                temp = answer[j];
                answer[j] = answer[j + 1];
                answer[j + 1] = temp;
            }
        }
    }
    
    return answer;
}

 

버블정렬은 활용도가 아주 많은것 같다. 

728x90
반응형