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

๊ณณ๊ฐ„์—์„œ ์ธ์‹ฌ๋‚œ๋‹ค/์Šคํ„ฐ๋””

[Kotlin] Selection Sort

์ง€์ •ํ•œ ์ž๋ฆฌ์— ํƒ์ƒ‰ ๋ฒ”์œ„(๋น„๊ต ๋Œ€์ƒ)์—์„œ ์ฐพ์€ ๋งž๋Š” ๊ฐ’(๊ฐ€์žฅ ์ž‘๊ฑฐ๋‚˜, ๊ฐ€์žฅ ํฌ๊ฑฐ๋‚˜)์„ ์ฐพ์•„ ๋„ฃ๋Š”๋‹ค.

๊ธฐ๋ณธ 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("--------------------------------------------")
}