Sorting: Bubble Sort
Contents
가장 기초적인 sorting 알고리즘인 bubble sorting 구현문제이다.
Problem
Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following three lines:
- Array is sorted in
numSwaps
swaps.,numSwaps
where is the number of swaps that took place. - First Element:
firstElement
, wherefirstElement
is the first element in the sorted array. - Last Element:
lastElement
, wherelastElement
is the last element in the sorted array.
Sorting의 가장 기본적인 bubble sort의 구현문제이다. $O(n^2)$의 complexity를 갖는 알고리즘으로 실무적으로는 사용이 어렵다. 다만 실무에서는 어차피 built-in sorting을 사용하거나 NumPy
같은 numerical computing package에서 최적화된 방법을 제공하므로 학습목적으로만 사용하는 알고리즘이다.
Answer
|
|
Explanation
계산비용이 큰 만큼 구현은 간단하다. Array를 처음부터 sweep하면서 가장 작은 수를 찾아 앞으로 가져오는 작업을 $n$번 반복한다. 이를 $n$개에 대해 해야하므로 $O(n^2)$이 된다.