본문 바로가기
Python

[백준] 2750번 : 수 정렬하기

by Leunco 2021. 12. 27.
문제 유형 : 정렬

 

[예시]

5
5
2
3
4
1

[출력]

1
2
3
4
5

 


1. 내 풀이
N = int(input())

_list = []
for i in range(N):
    tmp = int(input())
    _list.append(tmp)

_list = sorted(_list)

for i in _list:
    print(i)

입력받은 N 개수만큼 _list에 데이터를 입력받았다. for문을 이용해 하나씩 입력받았고, append() 함수로 _list 뒤에 하나씩 이어붙였다. 그 뒤 sorted()로 _list를 오름차순 정렬하고, for문으로 _list 값 하나씩 출력하였다.

 

2. 다른 풀이
** 핵심 아이디어
1. 데이터의 개수가 1000개 이하 → 기본적인 정렬 알고리즘을 이용


1) 선택 정렬 알고리즘

n = int(input())
array = list()

for _ in range(n):
    array.append(int(input()))
    
for i in range(n):
    min_index = i # 가장 작은 원소의 인덱스
    for j in range(i+1, n):
    	if array[min_index] > array[j]:
            min_index = j
    array[i], array[min_index] = array[min_index], array[i] # swap
    
 for i in array:
 	print(i)

(1) 선택 정렬 예시

 

(2) 정렬 실습 사이트

https://visualgo.net/en/sorting

 

Sorting (Bubble, Selection, Insertion, Merge, Quick, Counting, Radix) - VisuAlgo

VisuAlgo is free of charge for Computer Science community on earth. If you like VisuAlgo, the only "payment" that we ask of you is for you to tell the existence of VisuAlgo to other Computer Science students/instructors that you know =) via Facebook/Twitte

visualgo.net

위의 사이트에서 정렬이 어떻게 진행되는지 알 수 있다.

 

상단에서 어떤 정렬을 할지 결정한다.

 

하단의 <버튼을 클릭해 Create(A)로 list A에 데이터를 생성한다.

 

A를 생성한 뒤 Go 버튼을 누른다.

 

하단의 <버튼에서 Sort 버튼을 클릭하면 자동적으로 정렬이 시작된다.

 

 

2) 파이썬의 기본 정렬 라이브러리 이용

n = int(input())
array = list()

for _ in range(n):
	array.append(int(input())

array.sort()

for i in array:
	print(i)

 

 

출처 : 패스트캠퍼스 - 알고리즘 / 기술면접 완전 정복 올인원 패키지 Online

문제 출처 : https://www.acmicpc.net/problem/2750

 

2750번: 수 정렬하기

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

www.acmicpc.net

 

반응형

댓글