์ง์ ํ ์๋ฆฌ์ ํ์ ๋ฒ์(๋น๊ต ๋์)์์ ์ฐพ์ ๋ง๋ ๊ฐ(๊ฐ์ฅ ์๊ฑฐ๋, ๊ฐ์ฅ ํฌ๊ฑฐ๋)์ ์ฐพ์ ๋ฃ๋๋ค.
๊ธฐ๋ณธ swap
fun <T> ArrayList<T>.swap(firstIndex: Int, secondIndex: Int) {
val temp = this[firstIndex]
this[firstIndex] = this[secondIndex]
this[secondIndex] = temp
}
Selection Sort
fun <T: Comparable<T>> ArrayList<T>.selectionSort(showLog: Boolean = true) :ArrayList<T> {
if (this.size < 2) {
println("๋ฐฐ์ด ํฌ๊ธฐ : ${this.size}. ๋ฐฐ์ด ๊ทธ๋๋ก ๋ฐํ")
return this
}
for (currentPosition in 0 until this.lastIndex) {
var indexOfMin = currentPosition
for (indexOfComparison in currentPosition + 1 .. this.lastIndex) {
if (this[indexOfMin] > this[indexOfComparison]) {
indexOfMin = indexOfComparison
}
}
if (indexOfMin != currentPosition) {
this.swap(indexOfMin, currentPosition)
}
if (showLog) println("์ ๋ ฌ : $this")
}
return this
}
Test
fun main() {
val arrayList = arrayListOf(4, 1, 5, 2, 3)
testSelectionSort(arrayList)
}
fun <T:Comparable<T>> testSelectionSort(testList: ArrayList<T>) {
println("input: $testList")
println("result : ${testList.selectionSort()}")
println("--------------------------------------------")
}
'๊ณณ๊ฐ์์ ์ธ์ฌ๋๋ค > ์คํฐ๋' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฉด์ ] ์๋๋ก์ด๋ ๊ฐ๋ฐ์ ์์ด ๋ฉด์ ์ ์์ฃผ ์ฐ์ผ ์ ์๋ ์๋จ์ด (1) | 2024.11.11 |
---|---|
[Kotlin] ์ต๋๊ณต์ฝ์ & ์ต์๊ณต๋ฐฐ์ ๊ตฌํ๊ธฐ (0) | 2023.07.13 |
[Kotlin][Java] ByteArrays๋ฅผ 16์ง์(Hex) String์ผ๋ก ๋ณํ (0) | 2023.02.28 |
[์๋ฃ๊ตฌ์กฐ] ์ฐ๊ฒฐ ๋ฆฌ์คํธ (0) | 2023.02.04 |
[Kotlin]Bubble Sort (0) | 2023.01.12 |