KU COSE101 2017기말고사 3번 문제

1 minute read

             
2016 기출 1번 2번 3번 4번 5번  
2017 기출 1번 2번 3번 4번 5번  
2018 기출 1번 2번 3번 4번 5번 6번

정수의 배열을 조금 특별한 방법으로 정렬하고자 한다. 즉 정렬 후에 음의 정수가 먼저, 양의 정수가 나중에 출력되어야 하는데, 음의 정수는 내림차순으로, 양의 정수는 오름차순으로 정렬되어야 한다. 이를 구현하는데 필요한 함수 special_sort()를 구현하라. 예를 들어, 입력이 -1, 1, 3, -2, 2, 3 이라면 올바른 출력은 -1, -2, -3, 1, 2, 3이 되어야 한다.

#include<stdio.h>

void special_sort(int ary[], int n) {
	
}

int main()
{
	int ary[] = {-1, 1, 3, -2, 2, -3};
	int n = sizeof(ary)/sizeof(ary[0]);
	special_sort(ary, n);
	printf("special order:");
	for(int i=0 ; i<n ; i++){
		printf(" %d", ary[i]);
	}
}

예시답안
void special_sort(int ary[], int n) {
	int neg[50], pos[50];
	int negcnt, poscnt;
	int i,j,tmp;
	
	negcnt=poscnt=0;
	for(i=0 ; i<n ; i++){
		if(ary[i]>=0){
			pos[poscnt++]=ary[i];
		} 
		else{
			neg[negcnt++]=ary[i];
		}
	}
	
	for(i=0 ; i<negcnt-1 ; i++){
		for(j=0 ; j<negcnt-1-i ; j++){
			if(neg[j]<neg[j+1]){
				tmp=neg[j];
				neg[j]=neg[j+1];
				neg[j+1]=tmp;
			}
		}
	}
	
	for(i=0 ; i<poscnt-1 ; i++){
		for(j=0 ; j<poscnt-1-i ; j++){
			if(pos[j]>pos[j+1]){
				tmp=pos[j];
				pos[j]=pos[j+1];
				pos[j+1]=tmp;
			}
		}
	}
	
	for(i=0 ; i<negcnt ; i++) ary[i]=neg[i];
	for(i=0 ; i<poscnt ; i++) ary[negcnt+i]=pos[i];
}
원래 평소였다면 std::sort나 qsort를 쓰는데, 학교에서 그런거 안가르쳐줘서 ***느려터진*** bubblesort를 사용한다.
물론, 데이터의 크기가 작기 때문에 bubblesort를 써도 상관 없다.

pos와 neg 배열에 ary를 각각 나눠서 넣어준다.
그리고 각각을 내림차순, 오름차순으로 정렬하고
다시 그 값들을 ary에 넣어준다.

Comments