์ธ์ ํ ๋ ๊ฐ์ ์์๋ค์ ๋น๊ตํ๋ฉฐ ์ ๋ ฌํ๋ค.
๊ธฐ๋ณธ 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("----------------------")
}
'๊ณณ๊ฐ์์ ์ธ์ฌ๋๋ค > ์คํฐ๋' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฉด์ ] ์๋๋ก์ด๋ ๊ฐ๋ฐ์ ์์ด ๋ฉด์ ์ ์์ฃผ ์ฐ์ผ ์ ์๋ ์๋จ์ด (1) | 2024.11.11 |
---|---|
[Kotlin] ์ต๋๊ณต์ฝ์ & ์ต์๊ณต๋ฐฐ์ ๊ตฌํ๊ธฐ (0) | 2023.07.13 |
[Kotlin][Java] ByteArrays๋ฅผ 16์ง์(Hex) String์ผ๋ก ๋ณํ (0) | 2023.02.28 |
[์๋ฃ๊ตฌ์กฐ] ์ฐ๊ฒฐ ๋ฆฌ์คํธ (0) | 2023.02.04 |
[Kotlin] Selection Sort (0) | 2023.01.12 |