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