Part 03 – Sorting and Navigation | Difficulty: ⭐⭐☆☆☆
Why implement sorting yourself?
In coding tests, sorted() is often enough, but for interviews and some questions,
Directly explain how it works and trade-offs of the sorting algorithm, or
We demand that it be implemented.
Bubble/Insertion: Good for small data and almost sorted data
Quick Sort: Average fastest, excellent cache efficiency
Counting/Radix: O(n+k) without comparison
Only by implementing it yourself can you really understand “when and which alignment to choose.”
Learning Objectives
Can explain the principles of bubble, insert, merge, quick, count sort and time/space complexity.
Determine whether each alignment is stable and in-place.
Select an alignment that fits the given problem conditions (n size, data range, stability requirements).
Key concepts
Time/Space Complexity Comparison Table
Sorting Algorithm
best
average
worst
space
stable
In place
Bubble Sort
O(n)
O(n²)
O(n²)
O(1)
✅
✅
Insertion Sort
O(n)
O(n²)
O(n²)
O(1)
✅
✅
Merge Sort
O(n log n)
O(n log n)
O(n log n)
O(n)
✅
❌
Quick Sort
O(n log n)
O(n log n)
O(n²)
O(log n)
❌
✅
Counting Sort
O(n+k)
O(n+k)
O(n+k)
O(k)
✅
❌
Radix Sort
O(nk)
O(nk)
O(nk)
O(n+k)
✅
❌
k = range of values
Stable Sort
Whether the relative order of elements with the same key value is maintained after sorting.
Input: [(A,2), (B,1), (C,2)]
After stable sort: [(B,1), (A,2), (C,2)] ← A is before C (maintaining original order)
Unstable sort: [(B,1), (C,2), (A,2)] ← No order guarantee
When there are a lot of inputs, input() is very slow → Use sys.stdin
Slow if print() is called 1 million times → Use '\n'.join()
import sys
input = sys.stdin.readline
n = int(input())
arr = [int(input()) for _ in range(n)]
arr.sort()
print('\n'.join(map(str, arr)))
Problem 3: Baekjun 10989 – Sorting numbers 3 (Silver V)
Problem Description
Sort N numbers in ascending order.
Limitations
1 ≤ N ≤ 10,000,000 (10 million!)
1 ≤ number ≤ 10,000
Memory limit: 8MB
Approach
I only have 8MB of memory so I can't store all the numbers in the array!
One int = about 28 bytes (CPython)
10 million × 28 bytes ≈ 280MB → exceeded
Coefficient Sort Use:
Count array size: 10,001 × 4 bytes ≈ 40KB → No problem
Just count the number of occurrences of each number.
#core idea
count = [0] * 10001
for _ in range(n):
count[int(sys.stdin.readline())] += 1
result = []
for val, cnt in enumerate(count):
result.extend([str(val)] * cnt)
print('\n'.join(result))
Checklist before submission
2750: Did you implement it directly with bubble sort?
2751: Did you increase input speed by using sys.stdin?
10989: Did you use coefficient sorting within the 8MB memory limit?
Are edge cases (N=1, duplicate values) tested in all problems?
Model answer
See the reference solution below.
file
Description
boj_2750.py
Bubble Sort Implementation
boj_2751.py
Merge sort or fast input/output
boj_10989.py
Sort coefficients
Show the reference solution
Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.
boj_10989.pyPython
"""Baekjoon 10989 – Sorting Numbers 3
https://www.acmicpc.net/problem/10989
Time : O(n + k) k = 10,000
Space : O(k) Only using a count array (passes 8MB memory limit)
Constraints: N ≤ 10,000,000, 1 ≤ number ≤ 10,000
Memory 8MB → Storing all numbers exceeds limit!
Use counting sort to store only the counts"""
import sys
def main() -> None:
input_data = sys.stdin.buffer.read().split()
n = int(input_data[0])
max_val = 10_001
count = [0] * max_val
for i in range(1, n + 1):
count[int(input_data[i])] += 1
out = []
for val in range(1, max_val):
if count[val]:
out.append((str(val) + '\n') * count[val])
sys.stdout.write(''.join(out))
if __name__ == "__main__":
main()
boj_2750.pyPython
"""Baekjoon 2750 – Sorting Numbers
https://www.acmicpc.net/problem/2750
Time : O(n²) (Bubble Sort)
Space : O(1) (in-place)
Constraint: N ≤ 1,000 → O(n²) is sufficient"""
import sys
input = sys.stdin.readline
def bubble_sort(arr: list[int]) -> None:
"""Bubble sort (in-place)."""
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
def main() -> None:
n = int(input())
arr = [int(input()) for _ in range(n)]
bubble_sort(arr)
print('\n'.join(map(str, arr)))
if __name__ == "__main__":
main()
boj_2751.pyPython
"""Baekjoon 2751 – Sorting Numbers 2
https://www.acmicpc.net/problem/2751
Time : O(n log n) (Timsort / Merge Sort)
Space : O(n)
Constraint: N ≤ 1,000,000 → O(n²) causes time limit exceeded, O(n log n) required
Fast input/output (sys.stdin) essential"""
import sys
input = sys.stdin.readline
def main() -> None:
n = int(input())
arr = [int(input()) for _ in range(n)]
arr.sort() # Timsort O(n log n)
sys.stdout.write('\n'.join(map(str, arr)) + '\n')
if __name__ == "__main__":
main()