티스토리 뷰

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
let inputCount = Int(readLine()!)!
var inputs = [Int]()
for _ in 1 ... inputCount{
    inputs.append(Int(readLine()!)!)
}
//선택정렬
func selectionSort(array: inout [Int]){
    for i in stride(from: array.count - 1, through: 1, by: -1){
        var maxIndex = i
        for j in 0 ..< i {
            if(array[maxIndex] <= array[j]) {
                maxIndex = j
            }
        }
        let temp = array[maxIndex]
        array[maxIndex] = array[i]
        array[i] = temp
    }
}
 
//버블정렬
func bubbleSort(array: inout [Int]){
    for i in stride(from: array.count - 1, through: 0, by: -1){
        for j in 0 ..< i {
            if(array[j] >= array[j+1]){
                let temp = array[j+1]
                array[j+1= array[j]
                array[j] = temp
            }
        }
    }
}
 
//삽입정렬
func insertionSort(array: inout [Int]){
    for i in 1 ..< array.count {
        let temp = array[i]
        var index = i - 1
        while(index >= 0 && array[index] >= temp){
            array[index+1= array[index]
            index -= 1
        }
        array[index+1= temp
    }
}
 
//스위프트라이브러리
func swiftStdLibSort(array: inout [Int]){
    array = array.sorted { $0 < $1 }
}
 
selectionSort(array: &inputs)
//bubbleSort(array: &inputs)
//insertionSort(array: &inputs)
//swiftStdLibSort(array: &inputs)
 
for i in inputs{
    print(i)
}
cs


단순한 수 정렬 문제.


선택 정렬 등 O(n^2)의 시간복잡도를 갖는 알고리즘을 구현하여 풀어보라고 해서 


선택 / 삽입 / 버블 정렬 코드를 모두 작성해 보았다.



Swift에서 stride(from:through:by:) 함수를 사용하여 C 스타일과 비슷한 for문을 작성할 수 있다.


stride(from:to:by:)를 사용하게 되면 마지막 값은 제외하여 루프를 돈다.


'Algorithm > Baekjoon Online Judge' 카테고리의 다른 글

1110번 '더하기 사이클'  (0) 2018.02.22
1065번 '한수'  (0) 2018.02.22
1008번 'A / B'  (0) 2018.02.22
1001번 'A - B'  (0) 2018.02.22
1000번 'A + B'  (0) 2018.02.22
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함