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

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

[Kotlin]Bubble Sort

์ธ์ ‘ํ•œ ๋‘ ๊ฐœ์˜ ์š”์†Œ๋“ค์„ ๋น„๊ตํ•˜๋ฉฐ ์ •๋ ฌํ•œ๋‹ค.

๊ธฐ๋ณธ swap

fun <T> ArrayList<T>.swap(firstIndex: Int, secondIndex: Int) {
    val temp = this[firstIndex]
    this[firstIndex] = this[secondIndex]
    this[secondIndex] = temp
}

 Bubble sort

fun <T:Comparable<T>> ArrayList<T>.bubbleSort(showLog: Boolean = true) : ArrayList<T> {

    if (this.size < 2) {
        println("๋ฐฐ์—ด์˜ ํฌ๊ธฐ๊ฐ€ 2 ๋ฏธ๋งŒ. ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜.")
        return this
    }

    for (end in lastIndex downTo 1) {
        var swapped = false
        for(current in 0 until end) {
            if (this[current] > this[current + 1]) {
                this.swap(current, current + 1)
                swapped = true
                if (showLog) println("์ •๋ ฌ ์ง„ํ–‰ : $this")
            }
        }
        if (showLog) println("์ •๋ ฌ ์ค‘๊ฐ„ result : $this")
    if (!swapped) return this
    }

    return this
}

Test

fun main() {
    val arrayList = arrayListOf<Double>(4.6,5.0,1.1,2.3,3.0, 1.5)
    testBubbleSort(arrayList)
}

fun <T:Comparable<T>> testBubbleSort(testList: ArrayList<T>) {
    println("input : $testList")
    val result = testList.bubbleSort()
    println("result : $result")
    println("----------------------")
}