본문 바로가기
Problem Solving Log

[Baekjoon] 2750 : 수 정렬하기 (C++)

by TypeMIN 2022. 3. 1.
728x90

Baekjoon Online Judge 2750번 : 수 정렬하기


문제

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

입력

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

출력

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

예제 입력

5
5
2
3
4
1

예제 출력

1
2
3
4
5

코드

#include <iostream>

using namespace std;

int nums[1000];

void insert_sort(int a[], int n);
void bubble_sort(int a[], int n);

int main() {
  int N;
  cin >> N;
  for(int i = 0; i < N; i++){
    cin >> nums[i];
  }
  //insert_sort(nums, N);
  bubble_sort(nums, N);
  for(int i = 0; i < N; i++){
    cout << nums[i] << '\n';
  }
}

void insert_sort(int a[], int n){
  int temp, pos;
  for(int i = 1; i < n; i++){
    temp = a[i];
    pos = 0;
    for(int j = i - 1; j >= 0; j--){
      if(temp < a[j]){
        a[j+1] = a[j];
      }
      else{
        pos = j + 1;
        break;
      }
    }
    a[pos] = temp;
  }
}

void bubble_sort(int a[], int n){
  int temp;
  for(int i = n - 1; i > 0; i--){
    for(int j = 0; j < i; j++){
      if(a[j] > a[j+1]){
        temp = a[j+1];
        a[j+1] = a[j];
        a[j] = temp;
      }
    }
  }
}
728x90
반응형