1+ import Foundation
2+
3+ //merge_sort(A[p..r]) { # A[p..r]을 오름차순 정렬한다.
4+ // if (p < r) then {
5+ // q <- ⌊(p + r) / 2⌋; # q는 p, r의 중간 지점
6+ // merge_sort(A, p, q); # 전반부 정렬
7+ // merge_sort(A, q + 1, r); # 후반부 정렬
8+ // merge(A, p, q, r); # 병합
9+ // }
10+ //}
11+ var saved = 0
12+ func merge_sort( _ collection: inout [ Int ] , _ p: Int , _ r: Int ) -> Bool {
13+ if p < r {
14+ let q = Int ( floor ( Double ( p+ r) / 2.0 ) )
15+ if merge_sort ( & collection, p, q) { return true }
16+ if merge_sort ( & collection, q+ 1 , r) { return true }
17+ if merge ( & collection, p: p, q: q, r: r) { return true }
18+ }
19+ return false
20+ }
21+
22+ //
23+ //# A[p..q]와 A[q+1..r]을 병합하여 A[p..r]을 오름차순 정렬된 상태로 만든다.
24+ //# A[p..q]와 A[q+1..r]은 이미 오름차순으로 정렬되어 있다.
25+ //merge(A[], p, q, r) {
26+ // i <- p; j <- q + 1; t <- 1;
27+ // while (i ≤ q and j ≤ r) {
28+ // if (A[i] ≤ A[j])
29+ // then tmp[t++] <- A[i++]; # tmp[t] <- A[i]; t++; i++;
30+ // else tmp[t++] <- A[j++]; # tmp[t] <- A[j]; t++; j++;
31+ // }
32+ // while (i ≤ q) # 왼쪽 배열 부분이 남은 경우
33+ // tmp[t++] <- A[i++];
34+ // while (j ≤ r) # 오른쪽 배열 부분이 남은 경우
35+ // tmp[t++] <- A[j++];
36+ // i <- p; t <- 1;
37+ // while (i ≤ r) # 결과를 A[p..r]에 저장
38+ // A[i++] <- tmp[t++];
39+ //}
40+ //p = 0, q = 0, r = 1
41+ func merge( _ collection: inout [ Int ] , p: Int , q: Int , r: Int ) -> Bool {
42+ var tmp : [ Int ] = [ ]
43+ var i = p, j = q+ 1
44+ while i <= q && j <= r {
45+ if collection [ i] <= collection [ j] {
46+ tmp. append ( collection [ i] )
47+ i += 1
48+ } else {
49+ tmp. append ( collection [ j] )
50+ j += 1
51+ }
52+ }
53+ while i <= q {
54+ tmp. append ( collection [ i] )
55+ i += 1
56+ }
57+ while j <= r {
58+ tmp. append ( collection [ j] )
59+ j += 1
60+ }
61+ i = p
62+ for element in tmp {
63+ saved += 1
64+ if saved == ak [ 1 ] {
65+ print ( " \( element) " )
66+ return true
67+ }
68+ collection [ i] = element
69+ i += 1
70+ }
71+ return false
72+ }
73+
74+ var ak = readLine ( ) !. split { $0 == " " } . map { Int ( String ( $0) ) ! }
75+ var collection = readLine ( ) !. split { $0 == " " } . map { Int ( String ( $0) ) ! }
76+ if !merge_sort( & collection, 0 , ak [ 0 ] - 1 ) {
77+ print ( " -1 " )
78+ }
0 commit comments