๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“š Algorithm/Algorithm Note

์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ (Bubble, Insertion, Selection) Swift

Bubble Sort 

โ‘  ๋‘ ์ธ์ ‘ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋น„๊ต

โ‘ก ์•ž์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ๋’ค์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ณด๋‹ค ํฌ๋ฉด, ๋‘˜์˜ ์ž๋ฆฌ๋ฅผ ๋ฐ”๊ฟ”์ค€๋‹ค

 

func BubbleSort(_ array: inout [Int]) {
    
    let length: Int = array.count - 1
    guard length > 1 else { return }
    
    for i in 0..<length {
        var Swap: Bool = false
        for j in 0..<length - i - 1 {
            if array[j] > array[j + 1] {
                array.swapAt(j, j + 1)
                Swap = true
            }
        }
        if !Swap {
            break
        }
    }
}

var numArray = [3, 6, 12, 65, 23, 99, 25, 37]
BubbleSort(&numArray)
print(numArray)
// [3, 6, 12, 23, 25, 65, 99, 37]

 

 

 

Selection Sort

โ‘  ๋ฐ์ดํ„ฐ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์ฐพ๋Š”๋‹ค

โ‘ก ์ฐพ์€ ๊ฐ’์„ ๋ฐ์ดํ„ฐ ๋งจ ์•ž ๊ฐ’๊ณผ ๊ต์ฒด

โ‘ข ๋งจ ์•ž ๋ฐ์ดํ„ฐ๋ฅผ ์ œ์™ธํ•˜๊ณ  ์œ„ ๊ณผ์ •์„ ๋ฐ˜๋ณต

 

func SelectSort(_ array: inout [Int]) {
    
    let length: Int = array.count - 1
    guard length > 1 else { return }
    
    for i in 0..<length {
        var min = i
        for j in (i + 1)..<array.count {
            if array[j] < array[min] {
                min = j
            }
        }
        array.swapAt(i, min)
    }
}

var numArray = [3, 6, 12, 65, 23, 99, 25, 37]
SelectSort(&numArray)
print(numArray)
// [3, 6, 12, 23, 25, 65, 99, 37]

 

 

Insertion Sort 

โ‘  ์ •๋ ฌ์€ ๋‘ ๋ฒˆ์งธ ์š”์†Œ๋ถ€ํ„ฐ ์‹œ์ž‘

โ‘ก ๊ธฐ์ค€์ด ๋˜๋Š” index์™€ ์ธ์ ‘ํ•œ index๋ถ€ํ„ฐ ๋น„๊ตํ•˜๋ฉฐ ์‚ฝ์ž…

โ‘ข ์‚ฝ์ž…์ด ๋๋‚˜๋ฉด, ๊ธฐ์ค€ index์˜ ๋‹ค์Œ index๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์žก๋Š”๋‹ค

 

func InsertSort(_ array: inout [Int]) {
    
    let length: Int = array.count
    guard length > 1 else { return }
    
    for i in 1..<length {
        let n = array[i]
        
        for j in stride(from: i - 1, through: 0, by: -1) {
            if array[j] > n {
                array[j + 1] = array[j]
            } else {
                array[j + 1] = n
                break
            }
            
            if j == 0 { array[j] = n}
        }
    }
}

var numArray = [3, 6, 12, 65, 23, 99, 25, 37]
InsertSort(&numArray)
print(numArray)
// [3, 6, 12, 23, 25, 65, 99, 37]

 

728x90