A sort is formally defined as a rearrangement of a sequence of elements that puts all elements into a non-decreasing order based on the ordering relation.
정렬은 순서 관계를 바탕으로 모든 요소를 비감소 순서(non-decreasing order)로 배치하도록 요소들의 나열을 재배치하는 것으로 공식 정의됩니다.
An important concept in sorting is inversions. An inversion in a sequence is defined as a pair of elements that are out of order with respect to the ordering relation.
정렬에서 중요한 개념 중 하나는 '역전(inversion)'입니다. 수열에서의 역전이란 정렬 기준(순서 관계)에 어긋나게 배치된 요소의 쌍을 의미합니다.
The more inversions present, the more out of order the list is. In fact, the concept of inversions introduces an alternative definition of sorting: Given a sequence of elements with n inversions, a sorting algorithm is a sequence of operations that reduces inversions to 0.
역전이 많을수록 목록의 정렬 상태가 더 흐트러져 있음을 의미합니다. 사실 역전 개념을 활용하면 정렬을 다음과 같이 다르게 정의할 수도 있습니다. 즉, n개의 역전을 가진 요소 수열이 있을 때, 정렬 알고리즘이란 역전의 수를 0으로 줄이는 일련의 연산 과정을 말합니다.
정렬과 관련하여 다음에 살펴볼 중요한 개념은 정렬 알고리즘의 안정성(stability)입니다. 안정적인 정렬 알고리즘의 핵심 특징은 값이 같은 요소들의 상대적인 순서를 그대로 유지한다는 점입니다.
가장 작은 요소를 찾아 리스트의 맨 앞으로 이동시키는 과정을 반복한다.
장점: 직관적이고 구현하기 쉽다
최선,평균,최악 시간복잡도:
공간복잡도: (추가 공간을 사용하지 않는다)
안정 정렬이 아니다.
인접한 두 요소씩을 바꿔나간다. 전부 정렬될 때까지.
최악,평균 시간복잡도: (최선은 )
공간복잡도:
안정 정렬이다. (값이 같으면 인접 요소가 바뀌지 않기 때문)
요소들을 하나씩 훑으면서, 올바른 상대적 위치에 삽입한다.
최악,평균 시간복잡도: (최선은 )
공간복잡도:
안정 정렬이다.
그리고 두 가지의 장점이 있다.
(1) 거의 정렬된 배열에서는 필요한 swap이 적기 때문에 삽입 정렬이 빠르다.
(2) 작은 배열에서는 성능이 좋다. (많은 정렬 함수들에서 배열 크기를 확인하고, 특정 임계값보다 작으면 삽입 정렬을 수행한다.)
Merge Sort 랑 Quick Sort 는 Divide and Conquer 섹션에서 다룬다.
Java 에서 정렬
1. 배열 정렬
int[] nums = {5,2,8,1};
// 오름차순
Arrays.sort(nums);
// 내림차순
Arrays.sort(nums, Collections.reverseOrder());
// Customize (두 번째 값 기준 오름차순
int[][] pairs = {{1, 3}, {2, 1}, {3, 2}};
Arrays.sort(pairs, (a,b) -> Integer.compare(a[1],b[1]));
List<Integer> list = new ArrayList<>(Arrays.aslist(5,2,8,1));
Collections.sort(list);
list.sort(Collections.reverseOrder());