Algorithm
[백준/정렬] 2751 - 수 정렬하기 2
strawberry_toast
2019. 10. 6. 23:43
문제
N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.
입력
첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 숫자가 주어진다. 이 수는 절댓값이 1,000,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.
출력
첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.
예제 입력 1
5 5 4 3 2 1
예제 출력 1
1 2 3 4 5
https://www.acmicpc.net/problem/2751
2751번: 수 정렬하기 2
첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 숫자가 주어진다. 이 수는 절댓값이 1,000,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.
www.acmicpc.net
내 소스
#include <iostream>
using namespace std;
void max_heapify(int *a, int i, int n){
int j, temp;
temp = a[i];
j = 2*i;
while(j <= n){
if(j < n && a[j+1] > a[j])
j = j+1;
if(temp > a[j]) break;
else if(temp <= a[j]){
a[j/2] = a[j];
j *= 2;
}
}
a[j/2] = temp;
return;
}
void heapsort(int *a, int n){
int i, temp;
for(i = n; i >= 2; i--){
temp = a[i];
a[i] = a[1];
a[1] = temp;
max_heapify(a, 1, i-1);
}
}
void build_maxheap(int *a, int n){
int i;
for(i = n/2; i >= 1; i--){
max_heapify(a, i, n);
}
}
int main(int argc, const char * argv[]) {
int i, n;
cin >> n;
int *a = new int[n];
for(i=1; i<=n; i++){
cin >> a[i];
}
build_maxheap(a, n);
heapsort(a, n);
for(i=1; i<=n; i++){
cout << a[i] << "\n";
}
return 0;
}