문제

N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.

입력

첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 숫자가 주어진다. 이 수는 절댓값이 1,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.

출력

첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.

예제 입력 1

5
5
2
3
4
1

예제 출력 1

1
2
3
4
5

비슷한 문제

<백준 알고리즘> 2751번: 수 정렬하기 2

<백준 알고리즘> 10989번: 수 정렬하기 3


더보기

Solution

#include<stdio.h>
#include<stdlib.h>
#define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=(t))

int partition(int list[],int left,int right)
{
	int pivot=list[left], temp, low=left, high=right+1;

	do
	{
		do
			low++;
		while(low<=right&&list[low]<pivot);
		do
			high--;
		while(high>=left&&list[high]>pivot);

		if(low<high)
			SWAP(list[low],list[high],temp);
	}
	while(low<high);

	SWAP(list[left],list[high],temp);

	return high;
}

void quick_sort(int list[],int left,int right)
{
	if(left<right)
	{
		int q=partition(list,left,right);
		quick_sort(list,left,q-1);
		quick_sort(list,q+1,right);
	}
}
int main(void)
{
	int N, *list=NULL;

	scanf("%d", &N);

	list=(int *)malloc(N*sizeof(int));

	for(int i=0;i<N;i++)
		scanf("%d", list+i);

	quick_sort(list,0,N-1);

	for(int i=0;i<N;i++)
		printf("%d\n", *(list+i));

	free(list);
	return 0;

}
728x90

+ Recent posts